Geolocation API with HTML5

Geolocation API and a browser supporting HTML5 location feature, may help you to know geolocation of a visitor (not so much accurate, cause it doesn’t use GPS to get location).
How? Let’s take a look to a simple code:

function GeoHtml5()
{
	if (navigator.geolocation)
        navigator.geolocation.getCurrentPosition(onGetPosition,onErrorPosition);
	else
        alert("geo not supported");
}
 
function onGetPosition(geolocation)
{
    var latitude = geolocation.coords.latitude;
    var longitude = geolocation.coords.longitude;
    alert("Your lat: " + latitude + "\nYour long: " +  longitude);
}
function onErrorPosition()
{
    alert("Error on get position");
}

First function, detects if browser supports this feature. Second one is triggered when getting location is OK, second one when it’s not. I’m not going to explain inline code, because it’s very intuitive and simple.

Here is the code running.

If W3C and browser “companies” improves it, it could reduce a little bit more differences with mobile’s web-apps and native apps.

For more information, visit W3c’s Geolocation API site.

Leave a Reply

Your email address will not be published. Required fields are marked *