Introduction to the HTML5 Geolocation API

by | Jul 20, 2012

The Geolocation API is one of the most exciting new features of HTML5 for us GIS folk. In this section we’re going to look at how geolocation works, what capabilities it offers us and show how easy it is to build an application to retrieve the users location.

What is the Geolocation API?
So what is the Geolocation API?  Well, the first thing to note is that Geolocation is not actually part of the HTML5 spec, but it’s mentioned so often in conjunction with HTML5 you could easily be fooled into thinking so.  In a nutshell, the Geolocation API provides simple but powerful methods of both acquiring and using location data in web pages. That is, making web pages ‘location aware’.

The user’s location can be derived from a number of different sources depending on the technology they are using. For obvious reasons, this is mainly targeted at mobile devices – for the simple reason that they tend to change location frequently – but still works on the desktop.

The methods used for determining a user’s location include:

• GPS – for devices that support it
• Calculation of location by wi-fi SSIDs
• Calculation of location by triangulation with nearest cellphone masts
• Or even by your IP address – not very accurate

Geolocation is Device Dependent
Obviously this makes geolocation very device dependent.

The web browser or device works out what methods are open to it for determining location and then – importantly from a security perspective – the user is required to opt-in to start sharing their location data. What they opt in to is dependent upon the type of device they are using – whether it supports GPS, wi-fi, etc.

Because of these security considerations, most browsers will not let you run geolocation code on a local file system – it has to be delivered by a web server. So you will need to have access to a web server like IIS or Apache to start working with the Geolocation API.

Although geolocation is supported by most modern browsers, as with all HTML5 functionality you should provide fallback options. We would recommened the Modernizr javascript API for a very robust solution, as discussed briefly in module one. Or, you could look at the Google Gears API which provides location awareness for older browsers. (Note that Gears is no longer being developed by Google as they concentrate their own attention on HTML5 but the libraries are still available.)

Working with the Geolocation API

The Geolocation API is very simple to use.  First, you need to make sure that the browser you are targeting supports Geolocation. You could go to a website like caniuse.com but clearly a more robust solution is to check programmatically at runtime. If geolocation is not supported you can fail gracefully or consider alternatives as previously discussed.

If geolocation is supported, you need to access the navigator.geolocation object which provides the methods that will determine the user’s location.  Which method you call on the geolocation object will depend on whether you want to just grab the location as a one-off or monitor it continuously.

Whichever method you choose you will need to create callback functions to handle the results whether they be successes or failures. A callback function is a function that you pass by reference into a method. When the method completes it can then call back that function, passing in any required data.

Then, you need to do something with that data. And, being GIS folks we may just want to put it on a map!

Simple Example

Let’s build a simple geolocation application. We’ll start by building a simple HTML page.

As you can see from the above, my page consists simply of a heading and a blank paragraph element. I’ve given this element an ID of ‘myLocation’ so I can write information to it.

Within my body tag I am capturing the onLoad event. I want to make sure that all the DOM elements are loaded before any script I write attempt to interact with them. The event handler for this is the init() function in my script tags, which simply reports that the event has been fired and captured.

So the first thing we need to do is determine whether the browser supports the Geolocation API.

Within my init() function (code below) I have written some code to check for the existence of the navigator.geolocation object. If this object is null, the if statement will return false and write a message to the myLocation paragraph saying that Geolocation is not supported. But if the object exists, we can continue to work with the Geolocation API and we’ll write a message out to the user telling them so.

The next thing we need to do is call a method on our navigator.geolocation object and attempt to gauge the user’s current location.

There are two methods we can call to achieve this: getCurrentPosition() and watchPosition(). We’ll look at getCurrentPosition() first.

getCurrentPosition() is a one-shot: it retrieves the user’s location details once and that’s it. You might want to use this method if you are trying to locate the user’s nearest doctor or retail location.

watchPosition() is for tracking the user. It gets called continuously and returns new results every time the user changes position.

Using getCurrentPosition()
We’ll start off by using getCurrentPosition(). As you can see in the code below, I’ve created a local variable to store a reference to the navigator.geolocation object and specified two callback functions in the call to getCurrentPosition – one for success and one for failure.

I’ve stubbed out those functions with just an alert box to show us which function gets called. You’ll notice that both are passed an object as a parameter.  These contain the results – in the case of successful location retrieval – or error details if otherwise. We’ll implement them in a bit.

First of all, let’s see what happens when we run this. I’m going to copy this html file to my web server – which I need to do for security reasons – and then launch it from that location in my browser.

I’m running Google Chrome, but your experience should be similar with any Geolocation-compliant browser.

The first thing I see is a notification that my web server (localhost) wants to track my physical location. If I press deny, my error handler gets called and I get a message saying that there is an error.

If I press Allow, then I get a message saying that there have been some results – in other words, the browser has managed to guess my position based on one of the device-specific options available to it.

Let’s now unpack those results and see what it came up with.  If I analyze the object that gets passed through to my callback function I learn that it is an object of type GeoPosition and I can see how to unpack its coords collection and display my current position which is what I’ve done in the code example.

You’ll also observe that there are other entries there for heading, speed, etc which are not relevant to getCurrentPosition() but do make sense when we’re doing continuous monitoring using watchPosition().  The other main property on the Geoposition object is the timestamp. We can parse this to ascertain when location retrieval occurred.

Let’s see how accurate that result is, by plotting it on a map. At the time of writing I’m sitting with my laptop with wireless disabled in a town called Bicester (pronounced ‘Bista’) in the UK.  Geolocation however, thinks I’m right in the center of the city of Oxford, about 12 miles away! It must be using my IP address in its calculations – not terribly accurate as you can see.

 

Now if I turn on Wireless, I get much better results. This time geolocation has positioned me about 20 meters away from my actual position.

However, if I connect my laptop to a GPS unit via Bluetooth I get much better results – bang on, in fact!

Tracking with watchPosition()
As mentioned earlier, the other method you can use to retrieve location details is watchPosition(). The syntax for watchPosition() is very similar to getCurrentPosition(). It requires callback functions for success and failure but also lets you specify an options object.  This options object gives you access to three settings:

Timeout: the amount of time (in milliseconds) your application should wait to retrieve location details before raising an error

enableHighAccuracy: this setting is false by default. When set to true, geolocation will use every means at its disposal to retrieve the most accurate results. As a general rule, if you’re doing tracking with a mobile device (and it’s fairly unlikely you will be – think about it for a moment!) you should set this to ‘true’. Otherwise any GPS capability on your device may not be enabled and you’ll get sub-standard results.

maximumAge: This is the longest a current location value should remain cached before forcing retrieval of a new value.

Note that when we call the watchPosition() method we’re storing the return value in a variable called WatchID. WatchID contains a unique ID we can use to turn off tracking. We just call clearWatch() and pass in that ID to do this.

 

 

 

 

Categories

Recent Posts

Mark Lewin
Mark is an authorized Esri and CompTIA CTT+ certified instructor, Esri certified Web Developer Associate and experienced web development professional. In a career spanning over 15 years, Mark has built dozens of sophisticated web applications and taught others to do the same, and has a particular interest in web mapping. Highlights include the development of a highly complex volcanic ash cloud modeling system for the UK's Met Office and using ArcGIS Server and the Flex API, and a state of the art cell phone tracking system for a defense contractor using the ArcGIS Server API for JavaScript. He has taught hundreds of GIS professionals how to build custom applications using Esri's ArcGIS Server and open source platforms (MapServer, OpenLayers, Leaflet) and delivered geospatial software tutorials and demonstrations to thousands

Sign up for our weekly newsletter
to receive content like this in your email box.