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:
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.
Finally, the timeout error (error code 3) will occur if PositionOptions.timeout (if set) is exceeded.
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.