Using the Ti.GeoProviders framework for geolocation

The Ti.GeoProviders framework provides a multiprovider approach to reverse geolocation. With a variety of providers, the Ti.GeoProviders framework provides a common API for handling GeoNames.org, Google, and basicGeo geolocation operations.

The following recipe demonstrates how to use the Ti.GeoProviders framework and its associated providers. The following screenshots illustrate this recipe running on both an iPhone and an Android device:

Using the Ti.GeoProviders framework for geolocation

Getting ready

This recipe uses both CommonJS and native modules. These can be downloaded from the source code provided by the book, or individually through the links provided in the See also section at the end of this recipe. Simply copy the Ti.GeoProviders folder into the Resources folder of your project and then copy the modules folder into your project as shown in the following screenshot. Finally, copy the provider_picker.js file into the Resources folder of your Titanium project as also highlighted in the following screenshot:

Getting ready

After copying the file and folder mentioned here, you will need to click on your tiapp.xml file in Titanium Studio and add a reference to the bencoding.basicgeo module as shown in the following screenshot:

Getting ready

How to do it...

Once you have added native and CommonJS modules to your project, you need to create your application namespaces in the app.js file and use require to import the module into your code as the following code snippet demonstrates:

//Create our application namespace
var my = {
  picker : require('provider_picker'),
  currentProvider:null,
  providers:[
    require('./GeoProviders/geonames_geoprovider'),
    require('./GeoProviders/bencoding_geoprovider'),
    require('./GeoProviders/google_geoprovider')
  ]
};

Adding your API key

Many of the Geo Providers require an API key. The Ti.GeoProvider includes the addKey method to allow you to associate your API key before making a service call. The following snippet demonstrates how to add the API key demo to your service calls.

my.currentProvider.addKey('demo'),

Adding your purpose

To use location services in iOS requires a purpose or reason for the app to access the GPS. On the first request, this message will be presented to the user. The following code demonstrates how to add this purpose to the Ti.GeoProviders using the addPurpose method:

my.currentProvider.addPurpose('Demo of Geo Provider'),

Note

Android does not require the purpose be provided; in this case the purpose defined is not used when accessing the GPS.

Building the recipe UI

The following code snippet describes how to create the UI shown in this recipe's earlier screenshots:

  1. The first step is to create the Ti.UI.Window to which all visual elements will be attached.
    var win = Ti.UI.createWindow({
      backgroundColor: '#fff', title: 'Ti.GeoProviders', 
      barColor:'#000',fullscreen:false
    });
  2. Next a Ti.Map.View is added to the Ti.UI.Window. This is used to plot the location information provided by the GeoProvider.
    var mapView = Ti.Map.createView({
      top:140, bottom:0, width:Ti.UI.FILL,
      userLocation:false	
    });
    win.add(mapView);
  3. A picker control is then added to the Ti.UI.Window. This control contains a list of providers and a callback method to switch between them. When the user updates the selected picker, the lookup.updateProvider method is called to switch the active Ti.GeoProvider. See the Lookup functions section in this recipe for more details.
    var picker = my.picker.createPicker({
      top:30, height:40},lookup.updateProvider
    });
    win.add(picker);
  4. The findButton button is the final UI component added to the recipe's Ti.UI.Window. This Ti.UI.Button is used to run the recipe's reverse geolocation lookup.
    var findButton = Ti.UI.createButton({
      title:'Find Current Location', 
      left:10, right:10,top:30,height:40
    });
    win.add(findButton);

Running the reverse geolocation

For running the reverse geolocation, perform the following steps:

  1. When the user presses the findButton, the click event is fired and the following snippet is run:
    findButton.addEventListener('click',function(e){
  2. The first step in this section of the recipe is to check that a network connection is available. A network connection is needed to contact the Ti.GeoProvider web service to perform the reverse geolocation lookup.
      if(!Ti.Network.online){
  3. If no network connection is available, the user is alerted to this requirement and the lookup process is stopped.
        alert("You must be online to run this recipe");
        return;
      }
  4. The final step in this section of the recipe is to call the getCurrentAddress method of Ti.GeoProviders. The method will use the Ti.Geolocation API to obtain the device's coordinates, and then use the specific logic of Ti.GeoProviders to return an address object to the onSuccess callback method provided. If an error occurs during the geolocation process the onError callback method will be called and provide the error details. The following snippet demonstrates how to call the getCurrentAddress method:
      my.currentProvider.getCurrentAddress(
      lookup.onSuccess,lookup.onError);
    });

Lookup functions

Now perform the following steps:

  1. The lookup object is used in this recipe to display the results returned by the GeoProvider.
    var lookup = {
  2. Using the picker control discussed earlier, the user can change the recipe's Ti.GeoProvider. When the provider is changed, the updateProvider method is called with the new provider details to be loaded.
      updateProvider : function(providerKey){
  3. Based on the providerKey given, the updateProvider method will switch the my.currentProvider object reference. Provider-specific details such as API key details will also be handled as part of this method. The geo names provider snippet demonstrates how provider switching is performed in this recipe.
        my.currentProvider = my.providers[providerKey];
    
        if(my.currentProvider.providerName == 'geonames'){
          my.currentProvider.provider.addKey('demo'),
        }
  4. Cross-provider methods such as addPurpose are performed at the end of the updateProvider method as they are leveraged by all Ti.GeoProviders.
        my.currentProvider.addPurpose('Geo Demo'),
      },
  5. The addToMap method is used to create a map pin using the latitude, longitude, and address information provided by the GeoNames Ti.GeoProvider.
      addToMap: function(lat,lng,title){
        var pin = Ti.Map.createAnnotation({
          latitude:lat,longitude:lng,
          title:title
        });
        mapView.addAnnotation(pin);
  6. A region is created using the latitude and longitude information from the Ti.GeoProvider. The setLocation method is then called to zoom the Ti.Map.View to the pin's coordinates.
        var region = {latitude:lat,
        longitude:lng,animate:true,
        latitudeDelta:0.04,
        longitudeDelta:0.04};
        mapView.setLocation(region);
      },
  7. The onSuccess method is used to handle the successful return from the Ti.GeoProviders. This method is used to orchestrate all user interactions after the successful return from the Ti.GeoProviders.
      onSuccess : function(e){
        if(!e.found){
          alert("Unable to find your location");
          return;
        }
  8. The generateAddress method is used to create a value for the title variable. The title variable is then used in the creation of the map pin. As Ti.GeoProviders can contain different formats, the generateAddress function is used to create a formatted address to be used for display purposes.
        var title = my.currentProvider.generateAddress(e);
        lookup.addToMap(e.latitude,e.longitude,title);
      },
  9. The onError method is used by the Ti.GeoProviders to return error information if an issue occurred during the reverse geolocation process. All error details are accessible in the e argument.
      onError: function(e){
        alert("Error Details:" JSON.stringify(e));
      }
    };

See also

To learn more about the basicGeo Titanium module used in this recipe, you can review the following links:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.152.71