May 122011
 

Gone are the days when the web was a one-size-fits-all kind of global information vending machine. In the past few years, continuous efforts are being made towards making the web as local as possible, with websites being able to present content suited to the users browsing it.

One huge component of this new wave are the development of location aware websites. Websites which give relevant information without the user having to explicitly search for it. For e.g. A movie ticket booking website which can be used to book tickets in theatres all over the country. Very few people, if any would travel more than 20 km to watch a movie. Hence it makes business sense to display the theatres in the 20 km radius of the users location. Instead of subjecting the user to an information overload, the website is smart enough to simplify the entire process and cut down the time taken.

Geolocation isnt a new concept. Previously, websites used the IP address and did a lookup to get a rough idea of the user’s location. There were other methods like the locale setting too. So while framing the HTML5 spec, the W3C decided to arrive at a standard for providing the client’s location to the server which abstracts out the actual method used by the browser to determine it (Cell tower triangulation, IP address, GPS etc). Since its a privacy concern to reveal one’s location, the whole geolocation API depends on explicit permission separately provided for each website.

I created an example page which integrates Google Maps API and geolocation and displays a map as per the user’s location. Since not every browser would be able to support geolocation yet, I used the JS library Modernizr which detects whether the feature is supported by the end browser without us having to do the browser sniffing using the user agent. Here is the script code.

/************************************
 * Title: Geolocation API access
 * Author: Ganesh Ranganathan
 ************************************/

var map; //global variable for the map object
$(document).ready(function(){
	//this is the default latitude /longitude to be set on the map
	var latlng = new google.maps.LatLng(-34.397, 150.644);
	var myOptions = {zoom: 8,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP};

	//Map constructor which creates the map
	map = new google.maps.Map($('#map_canvas')[0],myOptions);

	//Modernizr is a JS library which lets us check if
	//the target browser supports these features
	if(Modernizr.geolocation)
	{
		printMsg('Waiting for permission from you',false);
		//The getCurrentPosition takes in two callbacks - one for
		//success and one for error. Both functions are defined anonymously
		//inside the method
		navigator.geolocation.getCurrentPosition(function(position){
			printMsg('Permission Granted: Your Coordinates are '+position.coords.latitude+
					 ' & '+position.coords.longitude);
			//This is executed if the getPosition is successfull. Moving the map to the user's location
			map.panTo(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
		},function(error){
			//This is executed if the getPosition is unsucesfull.
			//Show the error reason to the user
			switch(error.code)
			{
			case error.TIMEOUT:
				printMsg ("Error: Timeout",false);
				break;
			case error.POSITION_UNAVAILABLE:
				printMsg ("Error: Position unavailable",false);
				break;
			case error.PERMISSION_DENIED:
				printMsg ("Error: Permission denied",false);
				break;
			case error.UNKNOWN_ERROR:
				printMsg ("Error: Unknown error",false);
				break;
			}
		});
	}
	else //Print this message if GeoLocation itself isnt supported by the browser
		printMsg("geolocation is not supported on your browser",false)
});

//Helper function to set the status message to
//the span value
var printMsg = function(txt,append){
	if(!append)
		$('#statusMsg').text(txt);
	else{
		var existingText = $('#statusMsg').text();
		$('#statusMsg').text(existingText+'  '+txt);
	}
};

The getCurrentPosition method of the navigator.geolocation object takes in two functions as the parameters. First is the SuccessCallback and second is the errorCallback. The success callback is passed the position object which contains the location information like latitude and longitude. This is the simple markup for the page. Please note that the Modernizr, Google Maps, Jquery scripts are referenced in the order they are needed.


<script src="Scripts/modernizr-1.7.min.js" type="text/javascript"><!--mce:0--></script>
<script src="Scripts/jquery-1.6.min.js" type="text/javascript"><!--mce:1--></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"><!--mce:2--></script>
<script src="Scripts/scripts.js" type="text/javascript"><!--mce:3--></script>
<h1>Geolocation API with HTML5</h1>
<div id="status">
 <span id="statusMsg"> </span></div>

The demo page for this application can be seen at – http://www.ganeshran.com/Files/geolocationtry

Here is the application when its run for the first time in Chrome. As you can see it asks for permission from the user. Meanwhile the map is centered towards the default location.

If we allow the application to access our location, then the map moves to the user’s coordinates – Bangalore in my case. Here is a screenshot – this time in Firefox

Since its a standardized API, the same code works for mobile browsers as well. Here are some screenshots of the page running on the Android stock browser which is also geolocation compliant.

After granting permission