- Development considerations
- Using Location Services in your App
- Obtain the Current GPS Position
- Continually monitor the GPS position
- Use the Device's Compass
- Forward and Reverse Geocoding
In this chapter, you'll learn how to use Titanium's Geolocation API to retrieve GPS positioning and heading information from mobile devices. You'll learn iOS, Android, and Mobile Web specifics that will help you best balance accuracy with battery consumption. And you'll learn how to manage Geolocation listeners with respect to your application's lifecycle.
The position and heading APIs are part of the
Ti.Geolocation module, which contains all the functions, properties, and events necessary to handle location information. That namespace is further divided into the
Ti.Geolocation.MobileWeb namespaces, which provide platform-specific features. In the following sections, you'll learn how to use this API to perform the following activities:
- Detect if location services are available
- Obtain the current GPS position
- Continually monitor the GPS position
- Use the device's compass
- Configure location service properties
- Forward and reverse geocoding
You'll also learn best practices and caveats to consider when using location services in your apps. But first, let's dive into some platform specific considerations when using these services.
iOS Development Considerations
iOS users are prompted to grant or deny permission when your application attempts to use geolocation information. The system provides a generic prompt for that request. However, according to Apple's guidelines, you should provide a customized message to more clearly tell users why you're requesting their location. You should set the
Ti.Geolocation.purpose property equal to the string that will be shown to users.
Android Development Considerations
In general, testing geolocation code should be done on a device so that you accurately and realistically test your app in an environment close to a real-world usage scenario. If you plan to test your code in the emulator, you must ensure that the AVD includes GPS emulation, and you'll need to send simulated location coordinates to that AVD.
Adding GPS Support to an AVD
The Android emulated virtual devices (AVDs) created by Studio include geolocation hardware emulation. However, if you're using an AVD you defined yourself, such hardware emulation might not be provided. You can enable GPS emulation within the AVD by following these steps:
- Open the Android SDK and AVD Manager (found at
- Select your Titanium Android emulator and click the "Edit.." button
- In the "Hardware" section, see if "GPS support" is listed
** If it is, make sure the "Value" field it set to "yes"
- If not, click the "New..." button
- From the "property" list, select "GPS support"
- Click "OK"
- Make sure the "Value" field for "GPS support" it set to "yes"
- From the "property" list, select "GPS support"
- If not, click the "New..." button
- Click "Edit AVD" then click "OK" in the resulting dialog
- Restart your Android emulator, if necessary
Setting a Simulated Location with DDMS
By default, the AVDs (emulators) do not have a default mock location. You must specify a location to use during testing. This also technically a requirement on a device, however the likelihood is very high that you have used some app that has set a location already.
You use DDMS (the Dalvik Debug Manager) to send mock locations to the Android emulator. To do so, follow these steps:
- Open DDMS (found at
- Select your emulator from the list of devices in the left pane and click the "Emulator Control" tab in the right pane
- In the right pane, scroll down to the "Location Controls" section
- Click the "Manual" tab if it is not already selected
- While your location based app is running in the emulator, enter values for latitude and longitude and click "Send"
To get more information about providing mock locations to your Android emulator, be sure to check out the official Android documentation on the subject. It gives you details not only on manual mock locations, but also using the GPX and KML formats.
Once you've set the mock location, you must grant your app permissions to read that mock location data. You do this by adding an entry to the
AndroidManifest.xml file. Fortunately, Titanium will take care of this automatically for you. You can confirm that these permissions are present by going into your project's
build/android directory and checking the
AndroidManifest.xml file. Within the <manifest> section, you should see a line that looks like this:
Mobile Web considerations
For geolocation to work with Mobile Web, the user must be running a browser that supports the W3C's Geolocation API. The actual implementation of geolocation, and accuracy provided, is also a function of the user's browser as well as the device on which they're running that browser. As with iOS, Mobile Web apps will prompt users to grant permission to access your location. However, you cannot change the message displayed to users. That message is dependent on the browser he or she uses, but typically follows the form "www.example.com Would like to use your current location."
Using Location Services in your App
Using location services generally follows these three stages:
- Determine if location services are enabled and available.
- Configure the accuracy and listener mechanisms to use.
- Grab a one-time location or enable a location-listener to continually monitor a user's location.
- With a location-listener, actively manage the listener in coordination with the app's lifecycle.
Using location services can have a significant impact on a device's battery life, so it's important to use them in the most efficient manner possible. Power consumption is strongly influenced by the accuracy and frequency of location updates required by your application. The higher the accuracy you request, and the more frequently you request location updates, the more battery power that will be consumed.
Detect if Location Services are Available
To determine whether or not location services will be available to you on the current mobile device, you simply need to check the boolean property
Ti.Geolocation.locationServicesEnabled. Keep in mind, though, that on Android 2.2 and above, a low-precision "passive" location provider is enabled at all times, even when the user disables both the GPS and Network location providers. Therefore, this method always returns
true on such devices. With this in mind, the base skeleton of a locations based app might look something like this.
Configure the Accuracy and Frequency
The location services systems of the underlying platforms are very different, so there are significant implementation differences between the platforms. The basic methods of requesting location information and receiving location updates are essentially the same on all platforms. However, the method of configuring the accuracy and frequency of location updates is different for each platform.
iOS Geo Configuration
In iOS, the accuracy (and power consumption) of location services is primarily determined by the
Ti.Geolocation.accuracy property setting. You can set this property to one of the following values:
- ACCURACY_BEST (highest accuracy and power consumption)
- ACCURACY_THREE_KILOMETERS (lowest accuracy and power consumption).
(Note that the constants ACCURACY_HIGH and ACCURACY_LOW are Android-specific and may not be used with iOS.)
Based on the accuracy you choose, iOS uses its own logic to select location providers and filter location updates to provide location updates that meet your accuracy requirements. You can further limit power consumption on iOS by setting the
Ti.Geolocation.distanceFilter property to eliminate position updates when the user is not moving. That property accepts a distance in meters; when the user has moved approximately that distance, your app will receive location update events.
- accuracy - The target accuracy of all location data received. The following
Ti.Geolocationconstants represent the valid values for this property:
ACCURACY_BEST- Location data will be of the highest possible accuracy of which the device is capable
ACCURACY_HUNDRED_METERS- Location data will be accurate within 100 meters
ACCURACY_KILOMETER- Location data will be accurate within 1 kilometer
ACCURACY_NEAREST_TEN_METERS- Location data will be accurate within 10 meters
ACCURACY_THREE_KILOMETERS_- Location data will be accurate within 3 kilometers
- distanceFilter - The minimum change of position (in meters) before a
locationevent is fired. The default is 0, meaning that location events are continuously generated.
- headingFilter - The minium change of heading (in degrees) before a
headingevent is fired. The default is 0, meaning that heading events are continuously generated.
- preferredProvider - Allows you to specify the preferred method for receiving a location. The following
Ti.Geolocationconstants represent your possible choices:
PROVIDER_NETWORK- Give the network based location provider preference
PROVIDER_GPS- Give the GPS location preference
Using the event-driven location example at the beginning of this chapter, let's modify it to use some of the above properties.
Android Geo Configuration
Prior to Titanium Mobile 2.0, Titanium attempted to follow the iOS model on Android, but this didn't fit the native Android model well. Android offers a much richer geolocation model, with multiple location providers, distance filters, update frequencies, and so forth. In Release 2.0, three different location service mode are supported on Android: legacy, manual, and simple.
- Legacy mode is the mode that existed prior to 2.0. Legacy mode is used when you set the accuracy property to one of the iOS ACCURACY constants (see above).
This mode is deprecated on Android and should not be used for new development. In legacy mode, the specified accuracy value determines the minimum distance between location updates. If accuracy is set to ACCURACY_BEST, no distance filter is used on updates. In legacy mode, only a single location provider (GPS, network, or passive) is enabled at a time. You can specify a the location provider using the
Ti.Geolocation.preferredProviderproperty. You can also specifying a desired update frequency using the frequency property. The
frequencyproperties are not used in any other mode.
- Manual mode gives developers low-level control of location updates, including enabling individual location providers and filtering updates, for the best combination of accuracy and battery life. Manual mode is used when the
Titanium.Geolocation.Android.manualModeflag is set to
true. In manual mode, the accuracy property is not used, and all configuration is done through the
- Simple mode provides a compromise mode that provides adequate support for undemanding location applications without requiring developers to write a lot of Android-specific code. Setting
Ti.Geolocation.accuracyto either ACCURACY_HIGH or ACCURACY_LOW enables simple mode. In this mode the platform handles enabling and disabling location providers and filtering location updates.
See the http://developer.appcelerator.com/apidoc/mobile/latest/Titanium.Geolocation.Android-module.html for further Android-specific information.
Mobile Web Geo Configuration
Location services on Mobile Web operate similarly to the simple mode operations on Android. Setting accuracy property to ACCURACY_HIGH yields the best available location updates, with the highest power consumption. Using ACCURACY_LOW provides lower-quality location updates with lower power consumption. In addition to the accuracy setting, there are several Mobile Web-specific settings.
See the http://developer.appcelerator.com/apidoc/mobile/latest/Titanium.Geolocation.MobileWeb-module.html for further Mobile Web-specific information.
Obtain the Current GPS Position
With your app configured to use the appropriate level of platform-specific geolocation configuration, you're ready to work with location data. Many apps only infrequently need to use location services. Whether it's at app startup, on a button click, or at a timed interval, developers have a multitude of opportunities to actively query for location information.
Let's take a look at a very basic example. After asserting that location services are enabled, the
Ti.Geolocation.getCurrentPosition() function is used to query for location information. This function takes a single parameter; a callback function whose event object contains the requested location in its
coords property. This is an asynchronous call as the GPS functionality may take a moment to work, especially if this is the first time your app is accessing location. Also worth noting is that the location services might return a cached location (depending on the platform and the configuration choices you have made).
The output for a successful execution of the above app would look something like this:
Continually monitor the GPS position
Often you will want to know where a mobile device is at all times. The most common example of this is navigation for driving directions. To have the same constant awareness of a device's position in Titanium, you simply need to register the
location event with the
Here's a simple case showing how location data can be handled via event listener. You'll notice that the data is handled in a nearly identical manner to the
As with the
Ti.Geolocation.getCurrentPosition() example, the location data is returned in the event object's
coords property. The listener callback will be executed every time your device detects a new location.
Android Lifecycle Events
When monitoring location events continually in Android, apps will continue to receive events even when in the background. As mentioned above, this can be a major drain on the battery life of a mobile device. While this is sometimes the desired behavior, most apps only need location data while active.
In order to manage our location events such that we only receive them while our app is active, we need to take advantage of Titanium's access to the Android lifecycle events. There are three events of significance, each of which can be handled via
addEventListener() on the
destroy- This event is fired when your activity is destroyed. Location events should always be removed in this event.
pause- This event is fired when an activity moves to the background. If you intend to suspend your location data handling when your app is in the background, you need to remove location event listeners in this event.
resume- This event is fired when an activity comes to the foreground. If you previously removed location events in a
pauseevent, this is where you would add them again to reenable them.
Below is a demonstration of how you would handle these events in order to only manage
location events when your app is active. The key part to note is that pausing and resuming your
location event handling is the responsibility of the Android Activity object accessible through the Titanium API as
Use the Device's Compass
A mobile device's compass can be used to determine its heading. By using heading, the added dimension of direction can be added to a location based mobile app. With this addition, developers can add features like more robust navigation or even augmented reality.
Just as with location, Titanium has events and functions for both continual and one-time monitoring of heading. Also, check the API docs for platform-specific configuration information of heading options. For continual monitoring, the
heading event needs to be registered with the
Ti.Geolocation module. In the case of needing only the current heading, a simple call to the
Ti.Geolocation.getCurrentHeading() function is necessary. As you may have noticed, this is very similar to how location is handled.
The below includes both of the methods for determining heading mentioned above.
The console output of your program will contain the heading information, which will be sent continuously from the
heading event. The data for each heading entry will be structured in the following manner.
Forward and Reverse Geocoding
Another feature of location services that is built into the Titanium API is geocoding. This is the process of converting an address into a geographic location (forward geocoding), or vice versa (reverse geocoding). For example, let's say we wanted to know the latitude and longitude of the Appcelerator headquarters in Mountain View, California. All we need to do is use the
Ti.Geolocation.forwardGeocoder() function, giving it the address and a callback as parameters. Here's the code:
And here is the output of a forward geocoding of Appcelerator HQ. As you can see, it delivers the geographic location of the given address in latitude and longitude.
Now let's say we just have latitude and longitude and we want to figure out what places of interest are in the area. This case can occur if you accept these coordinates from user input, or if you want to get further information in your
location events. To do so, we use the
Ti.Geolocation.reverseGeocoder() function. To this function we pass a latitude, longitude, and callback function. Let's see what we get when we use the random coordinates (50,50), as in the below sample.
Here's the output:
While the above output shows only one place, you'll notice that the
places property is an array. This means that on any given call to
Ti.Gelocation.reverseGeocoder() you may receive a number of entries in the
places property, if multiple places are found in the area of your query.
In this chapter we learned how we can leverage a mobile device's native location services to add the context of a physical location to our apps. Using Titanium's APIs we are able to proactively query or passively listen for a device's current GPS position and heading. By using the configuration properties found in the
Ti.Geolocation module like
distanceFilter we can further refine a location based experience.
Finally, we learned how to use additional location based features like forward and reverse geocoding to get even more location details. In the next chapter, we'll learn how we can use the native mapping functionality of mobile devices via the
Titanium.Maps module. We'll be able to take the techniques learned in this chapter and apply them to the next in order to create a visual representation of our location data.