Umer Pasha Blogs

www.umerpasha.com

Finding GeoLocation using HTML5

on May 2, 2012

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: