Mobile applications are all the rage as smart phones are moving from smart to genius. Along with this movement is the movement to location aware applications. Your phone has GPS, your laptop has wifi, and your IP is known (generally) to be tied to a specific location. Given these new technologies being more commonplace the W3C has seen it fit to add an API to web design for Geo Location.
Although not technically a piece of the HTML5 spec, it is commonly used in conjunction with HTML5 and easy to use.
The geolocation API exposes three methods on the navigator object in javascript, two for getting location information about your user getCurrentPosition and watchPosition, and the other is a paired method for watchPosition, it is clearWatch.
The first, getCurrentPosition, returns a one time shot of where the user is. This is good for pinning a map or giving static directions. The second, watchPosition, continues polling at regular intervals to keep tabs on where the user is. This is perfect for giving dynamic directions, or tracking a movement. The two calls are mirrors of one another in that they both accept three arguments (success handler, error handler, geolocation options). The two calls are also both asynchronous, with a caveat that if this is a user’s first visit to your site they may be prompted to allow their position to be shared, this could cause the browser to stop loading.
The odd ball function here is clearWatch, which simply clears any watches you have assigned, in other words it stops tracking your user.
Now that we know the basics let’s dig in!
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function (position){
var lat = position.coords.latitude;
var lon = position.coords.longitude;
alert('Lat: '+ lat +' \nLon: '+ lon);
}
}
The example above is about as simple as it gets, a simple one shot to get the users coordinates and then output them to the browser.
That is all there is to Geolocation in the browser, pair it up with Google Maps API and you have an award winning geolocation application ready to please the world.