HTML5 and Geolocation
Friday 04 November 2011
One of the cool new features in HTML5 is Geolocation or the capability to determine where someone is. It turns out most modern browsers support the Geolocation API as you can see on CanIUse.com. Unfortunately Internet Explorer 8, the most popular version of IE at this moment, is the big exception.
The Geolocation API is very easy to use. The basic function to use is the getCurrentPosition() which is located on the geolocation object which in turn is located on the navigator object. It takes a callback for success that give you the location and a failure callback with a reason the location request failed.
I am using jQuery hear to execute the code when the page is loaded. I am also using Modernizr to check is the current browser supports the Geolocation API. Using Modernizr is highly recommended when you start working with HTML5 style features and need to check if the current browser supports a particular feature.
This is the complete page to render following map of my location.
So how accurate is it?
That really depends. On my laptop I am getting a position to with 100 meters of where I am, the location returned actually claims to be accurate to 87 meters. My laptop doesn’t have a GPS but I am using Wi-Fi and that results in a pretty decent location. On my phone the position is a lot better because it can actually use the GPS is needed. But on my desktop, connected through cables instead of Wi-Fi, the position is several kilometers of. So it very much depends on the device.
But my privacy
Fortunately your privacy is save. Before a browser returns your location it needs to get your permission. So no need to be afraid of websites trying to sniff your location without asking your permission first.