Tuesday 24 July 2012

How to locate yourself using HTML5 Geolocation (obtain current location's latitue/longtitude)

To locate your current position.

What you need is just the following JavaScript code.


var coordinates;
function updatePosition(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    coordinates = [lat, lon];
}

function handleError(positionError) {
    alert('Attempt to get location failed: ' + positionError.message);
}

var gps = navigator.geolocation;
gps.getCurrentPosition(updatePosition, handleError);
alert(coordinates);

Yeap, thats all what you need to get your current location's latitude and longtitude.
And it's works on ALMOST all browsers. (Argh,  android device before v2.1 not supported.)
Mind that, the latitude and longtitude obtained it's not 100% accurate.
It depends on ISP and carrier for the accuracy.

Example, PC browser that access through wired line ISP would obtain the nearest relay station's location. Where the wi-fi user gets a closer match.

No comments:

Post a Comment