Tag: Location

HTML5 Series - Location

Being able to get a users location opens up some great functionality especially when used on mobile devices that could be anywhere. HTML5 makes it really easy to capture the users latitude and longitude in just a couple of lines of JavaScript.

What's important to remember though is the user always has the option of denying your request for their location so error handling is very important.

First you need to check to see if the device actually support geolocation by doing navigator.geolocation

1if (navigator.geolocation) {
2 // success code to go here
3} else {
4 alert("location not supported");
5}

Next we need to call navigator.geolocation.getCurrentPosition to get the current location. As capturing a location isn't something that happens instantly (first the browser will check with the user that this is ok and then it may take a few seconds for the device to actually work out the location) you need to provide a function that will be called when the location has been established.

After that accessing the location is easy just look at the coords.latitude and cords.longitude properties on the object that was returned to your callback function.

1<script>
2 function getLocation() {
3 if (navigator.geolocation) {
4 navigator.geolocation.getCurrentPosition(function (location) {
5 document.getElementById("latitude").innerText = location.coords.latitude;
6 document.getElementById("longitude").innerText = location.coords.longitude;
7 }, function (error) {
8 alert(error.code);
9 });
10 } else {
11 alert("location not supported");
12 }
13 }
14</script>
15
16Latitude: <span id="latitude"></span>
17Logitude: <span id="longitude"></span>
18
19<button onclick="getLocation();">Get location</button>
20