Getting Geolocation from browser using HTML5

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434