Using the HTML5 Geolocation API

I spent some time today fiddling around with the HTML5 Geolocation API for an upcoming project I’m working on and I thought I’d share some stuff I learned. In this post, I’ll briefly go over the API and the variability in accuracy I experienced when testing on a few different devices/browsers.

Using the API

The Geolocation API is a high-level client-side API that returns a users longitude and latitude using the best available location information source (GPS, cell IDs, RFID, MAC address, Wi-Fi, bluetooth, or IP address). Here’s some code to get a users location:

Error Handling

Several errors need to be handled when using the geolocation API.

A permission denied error (error code 1) may occur if the user denies the location lookup request. Note that this error will also be triggered if the user chooses ‘always deny’ on an alternate website making a geolocation request.

A position unavailable error (error code 2) may occur if the call to navigator.getCurrentPosition() fails. I was able to trigger this error on my phone by disabling Google Location Services.

Accuracy

I experimented with the geolocation API on a few different browsers and devices. On my laptop, Chrome, Firefox, and Safari gave comparable results with an accuracy within 20 meters. IE, on the other hand, seemed to be be off by about 1.6 km. I was able to get down to within 5 meters on my cell phone (Galaxy Nexus) with GPS enabled.

Integrating with Google Maps

For the purposes of this demo, I used the coordinates returned by the API to plot the users current location using the Google Maps Static Maps API. You can see a demo of this here.