HTML5 Recipes: More on Geolocation

In an earlier recipe, we looked at Geolocation support in HTML5 Geolocation API. We covered the getCurrentPosition() method on the navigator.geolocation object that allowed to get a one-time location. Certain types of Location Based applications might need to track the user as he/she moves through an area. This could be useful in geo-fencing type applications where the user is tracked in a particular area and notifications can be sent if the user moves in or out of a predefined regions. In other words, we need our application to be notified whenever the users location changes.

The Geolocation API provides a function called watchPosition. This function takes exactly the same number and type of parameters as the getCurrentPosition function. But there are differences. It returns back a value, typically known as the Watch ID. This is used to notify to the application, that tracking has started. At any given point in time, if you wish to stop tracking the user, you can call the clearWatch() method and pass the Watch Id that was returned as part of the watchPosition() method. Note that, as with the getCurrentPosition() method, the watchPosition() method too takes the sucess callback method, the error callback method and the PositionOptions object. Whenever the location of the user changes, the browser will invoke the success callback method and pass the Position object into it, from where you can introspect the coords object to get the location details like latitude, longitude, etc.

Let us take a look at the code below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML GeoLocation Test</title>
<script type="text/javascript">
var watchID=0;

function startLocationTracking(){
	if (navigator.geolocation) {
		alert("Your Browser supports GeoLocation");
		watchID = navigator.geolocation.watchPosition(showCurrentLocation,errorHandler,{enableHighAccuracy: true});
	} else {
		alert("Your Browser does not support GeoLocation.");
	}
}

function showCurrentLocation(position){
	document.getElementById("mylocation").innerHTML = "Tracking your position --> Current Latitude : " + position.coords.latitude + " , Longitude : " + position.coords.longitude;
}

function errorHandler(error){
	  alert("Error while retrieving current position. Error code: " + error.code + ",Message: " + error.message);
}

function stopLocationTracking(){
	if (watchID > 0) {
		navigator.geolocation.clearWatch(watchID);
		alert("Stopped Tracking Location");
	}
}

</script>
</head>
<body>
<div id="main">
	<div id="mylocation"></div>
	<input type="button" value="Start Tracking Me" onclick="startLocationTracking()"/>
	<input type="button" value="Stop Tracking Me" onclick="stopLocationTracking()"/>
</div>
</body>
</html>

Let us break the code down now:

  • We have defined two buttons, “Start Tracking Me” and “Stop Tracking Me”. When the “Start Tracking Me” button is clicked, we invoke the startLocationTracking() method.
  • The startLocationTracking() method will first determine if geolocation support is present in the browser. If it is not, we simply end the exercise. If it is supported, we invoke the watchPosition() method. This method takes 3 parameters: success callback, error callback and a PositionOptions object as was explained in the earlier recipe. The key thing to note here is that an ID that we call the watchID is returned and we store that.
  • The success callback method will be invoked whenever a location is obtained. The browser is responsible for tracking the location and since we have used the watchPosition method, any changes in location will result in the success callback method getting invoked. The success callback method is passed a Position object, from which we extract out the coords attribute and show the latitude and longitude.
  • Any any point, when we wish to stop the tracking, we need to call the clearWatch method and pass the watchID in that. That is exactly what happens when we click the “Stop Tracking Me” button.

See it in action here.

Note: Retrieving the location continuously is an expensive operation in terms of power consumption on mobile devices. So be considerate about that in your applications.

Now that we have seen both the getCurrentPosition and watchPosition methods, a typical thing would be to hook up the location information that we have retrieved into a Google Map. This is extremely straightforward and shown below is a sample application that uses the getCurrentPosition to retrieve the current location of the user and show that on a Google Map.

Let us take a look at the code below:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
  html { height: 100% }
  body { height: 100%; margin: 0px; padding: 0px }
  #map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript">

function findMyCurrentLocation() {
	var geoService = navigator.geolocation;
	if (geoService) {
		geoService.getCurrentPosition(showCurrentLocation,errorHandler,{enableHighAccuracy: true});
	} else {
		alert("Your Browser does not support GeoLocation.");
	}
}

function showCurrentLocation(position){
	//Convert position --> Lat/Lon object
	var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);

	//Google Map options
	var myOptions = {
		      zoom: 8,
		      center: latLng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    };

    //Create the Google Map
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    //Plot where the user is via a Marker
	var usermarker = new google.maps.Marker({
										position: latLng,
										map: map,
										title: "You are here!"
										});

	map.setCenter(latLng);
	usermarker.setPosition(latLng);
}

function errorHandler(error){
	  alert("Error while retrieving current position. Error code: " + error.code + ",Message: " + error.message);
}
</script>
</head>
<body onload="findMyCurrentLocation()">
<div id="map_canvas" style="width:100%"></div>
</body>
</html>

Let us break the code down now:

  • In the onload function of the element , we invoke the findMyCurrentLocation() method. This method checks support for geolocation in the browser and then invokes getCurrentPosition method.
  • The success callback method i.e. showCurrentLocation is invoked when the location is successfully retrieved. We first extract out the Latitude and Longitude to create an object of type google.maps.LatLng.
  • We then create an Options object for Google Map with the zoom factor, where the center of the map should be i.e. our location and the map type. Finally we create the google.maps.Map specifying where we want it to be rendered along with its center co-ordinates and we plot the Marker indicating where the user is.

See it in action here.


HTML5 Geolocation Recipes

  1. Getting Started with Geolocation
  2. More on Geolocation

Back to HTML5 Series

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s