1.8. Using the GPS and Displaying a Position on a Map

Problem

You want to retrieve the device’s current GPS location and place a marker indicating the current position on a map.

Solution

One of the most common functionalities in any mobile application is to retrieve the device’s location through GPS or WiFi detection and then plot the current position on a map.

To read the device’s current GPS location, PhoneGap provides three useful functions: getCurrentPosition, watchPosition, and clearWatch. The second function provides frequent updates to the location as the user moves.

The device’s current location is returned via JavaScript objects. This information contains a timestamp of when the coordinates were retrieved and an object that contains all of the pertinent information in the coordinates. This enables the user to plot the location on a map (latitude, longitude, etc.).

The PhoneGap API doesn’t provide native support for maps, so the simplest solution to ensure that you support the most platforms is to integrate Google Maps API via their JavaScript API. While this will be a little bit slower, as it requires transferring the maps over the network, it is far less work than extending the application via a plug-in for the various smartphones.

Discussion

To begin, you must create a new HTML file called map.html inside of your assets/www directory. This file will contain some basic HTML to display the menu, as well as a placeholder for Google Maps API.

<!DOCTYPE HTML> <html> <head> <title>PhoneGap</title> ...

Get 20 Recipes for Programming PhoneGap now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.