Geolocation via Browser

During our developement of PowerHour.at we found a lot of ways to figure out the users Geolocation (Latitude, Longitude). We actually came to the decision that the most efficient and above all free way is to do it via Google’s AJAX API and/or the property window.navigator.geolocation that is currently supported by the latest browsers.

Google’s AJAX API

Firstly I would like to mention the possibility of IP address to geolocation translation offered by Google’s AJAX API due to the fact that it also works without the users explicit agreement. I will describe the inclusion of this solution in a few steps:

Implement AJAX API

At first you will need to implement Google’s AJAX API on your website (if you do not already have an official developer’s key you get one here).

<script src="http://www.google.com/jsapi?key=--YOUR-DEVELOPER-KEY--" type="text/javascript"><!--mce:0--></script>

Figuring out the geolocation

After including the necessary javascript file for the AJAX API you can simply use the tutorial on Google’s official code platform:
http://code.google.com/p/gmaps-samples/source/browse/trunk/clientlocation/clientlocation.html

Geolocation via browser

To implement this solution, you will at first need to figure out whether the user’s browser supports this property defined by the W3C. If the browser supports that way of figuring out the user’s geolocation you only have to write a few  lines:

    function FigureOutUsersLocation()
    {
         // Check whether the browser supports this way
         if(window.navigator['geolocation'])
         {
           	window.navigator.geolocation.getCurrentPosition(function(location)
		{
			if(location)
			{
				with(location.coords)
				{
					var latlng = new GLatLng(latitude, longitude);
                                        //Do something with users position
                                        alert(latlng.lat() + ", " + latlng.lng());
				}
			}
		},
		function(error)
		{
			//Handle error
		});
         }
    }

The disadvantage of this solution is the fact that the user has to agree explicitly that you are allowed to geolocate his device. This is done via a warning from the browser (e.g. in Firefox similar to a popup warning).

Leave a Reply

© 2009 - 2010 PowerHour - Hosted on AustroSolutions.at