Geolocation is one of the best new HTML5 APIs, so let’s see what we can do with it. In a nutshell, Geolocation allows you to give your current location information to the browser. Google use Geolocation a lot, especially for things like Google Maps, you’re bound to have seen the popups ‘This page would like to use your current location’. If so, you’ve experienced HTML5 Geolocation.
Table of contents
In this tutorial, we’re going to dive into HTML Geolocation and hook the position into Google Maps API, to show our current location on Google Maps! Sounds fun.
We’ll be using the geolocation object, which allows us to gather geographic information from the device. This looks like so:
We then need to hook this up with our Longitude and Latitude:
Let’s take this knowledge above and create a function out of it, hooking it into Google maps!
First we need to feature detect and find out if the browser supports Geolocation:
The above if statement uses a double-bang (!!), it’s not entirely necessary as it inverts the expression twice, converting the outcome to a boolean, true/false. You can feature detect without the double-bang and achieve the same result, it’s just a standard feature detection test that you can easily hook into a boolean later down the line.
With regards to the fallbacks (else statement), as we’re not building anything for production environment, I’m just going to provide a dull fallback saying your browser doesn’t support Geolocation, this isn’t progressive by any means - so if you’re going to use Geolocation for production, think about how you could provide a fallback, this might be plotting some default co-ords on a Google Map instead, with the message inside saying their browser doesn’t support - but I’ll keep it simple.
Google Maps API v3
Using the Google Maps API v3, we can create a Google Map on the fly and add our current position to it. Here’s the API:
You’ll notice the query string at the end of the script source says ‘sensor=true’, this is necessary for applications that determine the user’s location via a sensor.
Merging a simple Google maps basepoint and hooking it into our Geolocation, we are then able to create a function like the below:
Should Geolocation fail, or the service be unavailable, we should ideally provide some sort of notification. I haven’t done it in this in my example, but here’s how you can target different error codes:
Periodic updates of Geolocation position
IE9 and up supports Geolocation, with a good number of earlier modern browser versions supporting it too. Mobiles are pretty great with geolocation, and you could even use the aforementioned watchPosition method and walk about to see your position moving!