Getting Geolocation from browser using HTML5

By | June 14, 2012

As we are getting inclined more and more towards devices, browsers are trying to do their best to actually implement features to suit the needs. HTML5 introduces GeoLocation APIs to the browser which enables you to get the location of your position directly using javascript.

In spite being very much premitive, browsers are capable of detecting the actual location of the user using either WIFI, satellite or other external sources if available. As a programmer you just need to call the location API and everything is handled automatically by the browser.

As geolocation is sensitive information, it is important to ask the user for permission.  Lets look into the code below :

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latLng = "{" + position.coords.latitude + "," + position.coords.longitude + "with accuracy: " + position.coords.accuracy;
alert(latLng);
}, errorHandler);
}

Here in the code we first detect whether geolocation api is available to the current browser. If it is available, we can use getCurrentPosition to get location of the current device and the accuracy of the position as well.

We can also use navigator.geolocation.watchPosition to continue watching the device location at an interval when the device is moving from one place to another.

I hope this post comes helpful.
Happy coding.