Umer Pasha Blogs

www.umerpasha.com

Finding GeoLocation using HTML5

HTML5 is really fun. Its like combining old school coding with ease of HTML and technology of the future.

Today I tried out geolocation services within HTML5. Turned out it is as easy as anything!

First you need to check if your browser supports that aspect of HTML5. As always….. i prefer Chrome over IE 😛

Here is the required Javascript:

window.onload = getMyLocation;

function getMyLocation() {

if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(showLocation);

}

else {

alert(“Sorry, no geolocation support”);

}

}

The following JS will actually determine your location. I am assuming you have a div in HTML named “mylocation”. That is where the coordinates will appear:

 

function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

var div = document.getElementById(“mylocation”);
div.innerHTML = “Latitude: ” + latitude + “, Longitude: ” + longitude;
div.innerHTML += ” (with ” + position.coords.accuracy + ” meters accuracy)”;
}

 

And that is about it….. this is the very basic information though but a good starting point. You can do a lot more than this…. calculate distance, convert distance units, map it on google maps etc.

Good luck integrating!!!

Advertisements
Leave a comment »