Skip to content

February 14, 2012

2

Geolocation & jQuery Mobile Maps

by nady

This tutorial presents how to use the Geolocation API from PhoneGap and how to show your position on Google Maps using jQuery Mobile Maps.

Final result:

phonegap geolocation jquery mobile maps

Download Sources

To setup a new project follow the tutorial for basic cross-platform mobile app.

After you have your starting project in place, open index.html and make your page code look like this:

<div data-role="page">
	<div data-role="header" data-position="fixed">
		<h1>DigitalNoiz</h1>
	</div>
	<div data-role="content">
		<h2>Geolocation</h2>
		<div id="map_canvas"></div>
		<div id="geolocation"></div>
	</div>
</div>

The map_canvas div is a wrapper in which we’ll put the Map and the geolocation div will list a table with geolocation properties that your device supports.

Open js/script.js file and create the function getPosition() that will get the current position and it will show the map, run this function when PhoneGap is ready to use in onDeviceReady().

function onDeviceReady(){
	getPosition();
}

Common sources of getting location information are from GPS (Global Positioning System) and from network signals. This Geolocation API is based on W3C Geo location API Specification.

The function navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions) is an asynchronous function that returns the device’s current position as a Position object. The Position object is passed as parameter to the geoSuccess callback function. If an error occurs the geoError callback function is invoked with a PositionError object as parameter. geoOptions is an optional parameter to customize the retrieval of the location.

Position properties

coords – a set of geographic coordinates. (Coordinates)
timestamp – timestamp for coords in milliseconds. (DOMTimeStamp)

Coordinates properties

latitude – latitude in decimal degrees. (Number)
longitude – longitude in decimal degrees. (Number)
altitude – height of the position in meters above the ellipsoid. (Number)
accuracy – accuracy of the latitude and longitude in meters. (Number)
altitudeAccuracy – accuracy of the altitude in meters. (Number)
heading – direction of travel specified in degrees relative to the true north. (Number)
speed – current ground speed of the device, meters per second. (Number)

PositionError properties

code – predefined codes like PERMISSION_DENIED, POSITION_UNAVAILABLE, TIMEOUT
message – message describing the error

geoOptions properties

enableHighAccuracy – the application would like to receive the best possible result. (Boolean)
timeout – the maximum amount of time in milliseconds that is allowed to pass until the geoSuccess callback function is invoked. (Number)
maximumAge – a cached position that is not older than the specified time in milliseconds. (Number)

// get current position and show map
function getPosition(){	
	var geoOptions = { enableHighAccuracy: true, timeout: 10000 };
	navigator.geolocation.getCurrentPosition(function(position){ // geoSuccess
		// we have the position		
	}, function(error){ // geoError
		navigator.notification.alert('error: ' + error.message + '\n' + 'code: ' + error.code);
	}, geoOptions);
}

Let’s see which of the Coordinates properties are available for our device and list them in a table. Add the following code into the geoSuccess callback:

var geolocation = $('#geolocation');
geolocation.html('<table></table>');

var table = geolocation.find('table');
if(position.coords.latitude)
	table.append('<tr><th>Latitude</th><td>' + position.coords.latitude + '</td></tr>');
if(position.coords.longitude)
	table.append('<tr><th>Longitude</th><td>' + position.coords.longitude + '</td></tr>');
if(position.coords.altitude)
	table.append('<tr><th>Altitude</th><td>' + position.coords.altitude + '</td></tr>');
if(position.coords.accuracy)
	table.append('<tr><th>Accuracy</th><td>' + position.coords.accuracy + '</td></tr>');
if(position.coords.altitudeAccuracy)
	table.append('<tr><th>Altitude Accuracy</th><td>' + position.coords.altitudeAccuracy + '</td></tr>');
if(position.coords.heading)
	table.append('<tr><th>Heading</th><td>' + position.coords.heading + '</td></tr>');
if(position.coords.speed)
	table.append('<tr><th>Speed</th><td>' + position.coords.speed + '</td></tr>');
if(position.coords.timestamp)
	table.append('<tr><th>Timestamp</th><td>' + new Date(position.timestamp) + '</td></tr>');

Now that we have the coordinates let’s see them in Google Maps.
Download jQuery Mobile Maps and copy the minified file jquery.ui.map.min.js into mylibs. Open index.html and add in the <head> after the PhoneGap setup:

<!-- jQuery UI Map v3 -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="mylibs/jquery.ui.map.min.js"></script>

The css/style.css should look like this:

h2{
	text-align:center;
	color:#060;
}

table{
	width:100%;
	font-size:18px;
}

tr:nth-child(odd){
	background:#ccc;
}

th{
	text-align:left;
}

#map_canvas{
	width: 100%;
	height:250px;
	margin-bottom:10px;
}

In js/script.js at the end of geoSuccess callback function add:

/* show position on map */
var map_canvas = $('#map_canvas'); 
map_canvas.gmap(
	{'center' : position.coords.latitude + ',' + position.coords.longitude,
	'zoom' : 12,
	'disableDefaultUI':true,
	'callback':function(){
		var self = this;
		var marker = self.addMarker({ 'position' : this.get('map').getCenter() });
		marker.click(function(){
			self.openInfoWindow({ 'content' : 'This is your current location' }, this);
		});
	}	
});

This creates a map that is centered on the device’s position. The callback function adds a marker to the position and when the marker is clicked it shows an window with the message “This is your current location”.

In order to test if the device is connected to a network and if it can create the map use events from the PhoneGap Network Connection and Events.

Enjoy!

Read more from Mobile
2 Comments Post a comment
  1. Mar 23 2012

    Hi,
    I’ve followed your tutorial and create a project with your source files in Xcode – but it doesn’t seem to work. The index.html page loads – but no map or geo location data. I’ve tried trouble shooting in firebug but no errors occur.

    Is something missing?

    Thanks,
    Craig

    Reply
    • nady
      Mar 28 2012

      Hi,
      First of all you can’t use firebug as a debugging tool, because this is a mobile application, to debug use the console from xcode.
      In simulator you may get a timeout error if it tries to get the position from the gps sensor. You should try this example on your device.
      Make sure you change the phonegap-1.4.1.js with the version that you have installed and set it correctly in index.html

      Reply

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments