Geolocation

I know this is not very spooky post for Halloween. Unless, of course, you were sitting there this evening thinking to yourself, I wonder how you make a web page location aware and happened across my post.

Anyway, back to the subject. Using HTML 5 you can now include the user’s location within your application. The Geolocation API was included in HTML5 although not strictly as part of the HTML5 specification. You can now use the power of a location aware device to know where your user is and provide content relevant to them.

It is quite simple to do and this article explains the code that you need to do that with an example of its usage plotting the location on Google Maps.

Geolocation

First up here’s the basic HTML structure. I have added a title to the head section and a paragraph tag to the body section that I’ve given the identity of “msg”.

<!DOCTYPE HTML>
<html>
<head>
<meta charset=”utf-8″>
<title>Geolocation API</title>
</head>
<body>
<p id=”msg”></p>
</body>
</html>

The Geolocation functionality is via JavaScript so in the “head” section you’ll need to add some script tags and three functions.

<script>
function init()
{
  if(navigator.geolocation){
    document.getElementById(“msg”).innerHTML = “Geolocation is searching for you…”;
    navigator.geolocation.getCurrentPosition(foundPosition, errorPosition);
  } else {
    document.getElementById(“msg”).innerHTML = “Your browser does not have Geolocation functionality”;
  }
}
function foundPosition(position) {
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  document.getElementById(“msg”).innerHTML = “Geolocation found you approximately at…<br />Latitude: ” + lat + “, Longitude: ” + long + “.”;
}
function errorPosition(position) {
  document.getElementById(“msg”).innerHTML = “Sorry, Geolocation cannot approximate your location at this time.”;
}
</script>

I’ve called the first function “init” and it takes no arguments (an argument is something such as a value that you will pass into a function when you call it) but you can name it anything you like. This function is what we will call as the final action when the page loads to enable our Geolocation request. The init function asks if your browser supports this functionality and if it doesn’t it gives an appropriate error message.

If it does support Geolocation functionality it then changes the message paragraph text to let you know it is searching and then asks for your location which prompts you to share your location from your browser (see screenshot below). It then displays the results or an error message if something went wrong.

Geolocation 1

The “getCurrentLocation” function takes two functions as arguments. In this case I’ve called them “foundPosition” and “errorPosition”. Each of those functions must accept a position argument that contains either the current location or an error message.

If you run the script now, you will get nothing returned as we haven’t added the request to the init function when the page is loading. You can either add onload=init; to the script below the closing parenthesis of the init function or you can add an onLoad=”init();” attribute to the body tag. I’ll do it that way so my script section is clean (only contains functions).

Here’s the full script so far.

<!DOCTYPE HTML>
<html>
<head>
<meta charset=”utf-8″>
<title>Geolocation API</title>
<script>
function init()
{
  if(navigator.geolocation){
    document.getElementById(“msg”).innerHTML = “Geolocation is searching for you…”;
    navigator.geolocation.getCurrentPosition(foundPosition, errorPosition);
  } else {
    document.getElementById(“msg”).innerHTML = “Your browser does not have Geolocation functionality”;
  }
}
function foundPosition(position) {
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  document.getElementById(“msg”).innerHTML = “Geolocation found you approximately at…<br />Latitude: ” + lat + “, Longitude: ” + long + “.”;
}
function errorPosition(position) {
  document.getElementById(“msg”).innerHTML = “Sorry, Geolocation cannot approximate your location at this time.”;
}
</script>
</head>
<body onLoad=”init();”>
<p id=”msg”></p>
</body>
</html>

Geolocation 2

So I’ve viewed this web page on my PC and that device is not location aware. The latitude and longitude do not represent my position but they represent a location aware device somewhere on my route out to the internet. It’s actually above a betting office about 20 miles away. If I run the same script from the same location using a location aware device then the results are different and you will see that in a later screenshot when we add a Google map to the page.

Google Maps

It is very simple to add Google Maps and combine this with Geolocation. You can already find the location using the Geolocation API and Google give you everything you need for the Maps by connecting to an external script (if you prefer you can also use Bing Maps).

Add the following above your other “script” tag.

<script src=”http://maps.google.com/maps/api/js?sensor=false”></script>

Add the following to the end of your foundPosition function before the closing parantheses.

  var latlong = new google.maps.LatLng(lat, long);
  var options = { zoom: 16, center: latlong, mapTypeId: google.maps.MapTypeId.ROADMAP };
  var map = new google.maps.Map(document.getElementById(“map”),options);
  var marker = new google.maps.Marker({position: latlong, map: map, title:”You’re here”});

Finally, add a div tag to the body section of you page with an identity of “map” and with a size set in the style attribute.

<div id=”map” style=”width:600px;height:400px”></div>

Geolocation 3

This is pretty accurate although I’m standing on the other side of the road with my iPad.

I’m not going to explain the Google Maps code as you can find the most up to date information on their website. All I have basically done here is add a link to the Google map script library, pass the Geolocation on to a new map and add that map to the page.

I hope you found that useful and you can try it yourself Geolocation Tester.

If you are interested the full script is shown below or you can download the HTML file in a zip file Geolocation HTML5 Test File.

<html>
<head>
<meta charset=”utf-8″>
<title>Geolocation API</title>
<script src=”http://maps.google.com/maps/api/js?sensor=false”></script>
<script>
function init()
{
  if(navigator.geolocation){
    document.getElementById(“msg”).innerHTML = “Geolocation is searching for you…”;
    navigator.geolocation.getCurrentPosition(foundPosition, errorPosition);
  } else {
    document.getElementById(“msg”).innerHTML = “Your browser does not have Geolocation functionality”;
  }
}
function foundPosition(position) {
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  document.getElementById(“msg”).innerHTML = “Geolocation found you approximately at…<br />Latitude: ” + lat + “, Longitude: ” + long + “.”;
  var latlong = new google.maps.LatLng(lat, long);
  var options = { zoom: 16, center: latlong, mapTypeId: google.maps.MapTypeId.ROADMAP };
  var map = new google.maps.Map(document.getElementById(“map”),options);
  var marker = new google.maps.Marker({position: latlong, map: map, title:”You’re here”});
}
function errorPosition(position) {
  document.getElementById(“msg”).innerHTML = “Sorry, Geolocation cannot approximate your location at this time.”;
}
</script>
</head>
<body onLoad=”init();”>
<p id=”msg”></p>
<div id=”map” style=”width:600px;height:400px”></div>
</body>
</html>

Related articles

This is part of a series of articles covering the new features of HTML5. You can find an up-to-date list of those from the Development – HTML5 category.

Location aware content in your HTML5 web page

Leave a Reply