Super-simple Geolocation

“Remember, no matter where you go, there you are.” ― Buckaroo Banzai

Over the past several years mobile devices have brought us a lot of new great features and capabilities, things that people now are starting to expect from computing devices. Features like touch-capability, then multi-touch, GPS to tell where the device (and user) is, motion- and light-sensing, device orientation, access to the device’s camera, and even more. Wouldn’t it be great if web developers had access to all of those amazing new device features? Well, some of that is possible right now.

An extremely useful device feature is geolocation, a web API that allows you to see where in the world a device is. People sometimes call this “HTML5 Geolocation”, but then those people are snarked at by single-serving websites, so we’ll just call it “geolocation” or “the Geolocation API”. Geolocation is one of the device APIs that is fairly widely supported right now, and as we’ll see, is also pretty easy to get started with.

First things first

The first thing you want to do is test for browser support, because if the browser doesn’t support the Geolocation API then you might want to do something different like returning an error message and/or presenting alternate content.

You might see a variation on this syntax recommended for testing geolocation support:

[js]
if(!navigator.geolocation){
// no geolocation :(
}else{
// geolocation is supported :)
}
[/js]

Unfortunately that method of testing triggers a couple of different browser bugs, including a memory leak in IE9, a false positive in Firefox versions before 8, and disabling caching in Webkit. Who knew such a simple chunk of JavaScript could cause so many problems? Thankfully, the solution is easy (thanks to the Modernizr team for pointing to the right way to do this):

[js]
if(‘geolocation’ in navigator){
// geolocation is supported :)
}else{
// no geolocation :(
}
[/js]
Much better.

Getting the device’s current position with geolocation.getCurrentPosition()

This next step is almost too easy. Once we know that geolocation is supported and that the navigator.geolocation object exists we can start using its methods, which include getCurrentPosition().

[js]
/**
getCurrentPosition() accepts 3 arguments:
a success callback (required), an error callback (optional), and a set of options (optional)
**/

var options = {
// enableHighAccuracy = should the device take extra time or power to return a really accurate result, or should it give you the quick (but less accurate) answer?
enableHighAccuracy: false,
// timeout = how long does the device have, in milliseconds to return a result?
timeout: 5000,
// maximumAge = maximum age for a possible previously-cached position. 0 = must return the current position, not a prior cached position
maximumAge: 0
};

// call getCurrentPosition()
navigator.geolocation.getCurrentPosition(success, error, options);

// upon success, do this
function success(pos){
// get longitude and latitude from the position object passed in
var lng = pos.coords.longitude;
var lat = pos.coords.latitude;
// and presto, we have the device’s location! Let’s just alert it for now…
alert(“You appear to be at longitude: ” + lng + ” and latitude: ” + lat);
}

// upon error, do this
function error(err){
alert(‘Error: ‘ + err + ‘ :(‘); // alert the error message
}
[/js]
And that’s basically it! I should note that geolocation is always opt-in, once you call getCurrentPosition() then the user will be presented the option to choose whether to share location info or not. How that looks varies from browser-to-browser, but here’s the Chrome version:
infobar and here’s what it looks like in Firefox:
Screen Shot 2013-10-26 at 11.42.23 PM

As-promised, the super-simple version

Here’s the code distilled down to only what’s truly required to get a device’s latitude and longitude and store both of those values in JS variables.

[js]
if(‘geolocation’ in navigator){
navigator.geolocation.getCurrentPosition(success);
}
function success(pos){
var latitude = pos.coords.latitude;
var longitude = pos.coords.longitude;
}
[/js]

Of course you’d want to include some of the failure and error handling, and then actually do something with the coordinates you get back. More about that in an upcoming post, where I will cover using this technique to show where the user currently is on a map, using Leaflet.

CodePen Style

NOTE: You can check out the code in the pen below, but the geolocation will NOT work when it’s embedded in an iframe like below (this is due to an intentional limitation in CodePen). To try it out you can view this on CodePen.

Check out this Pen!

More resources

MDN – using Geolocation
Dive into HTML5 – You Are Here (And So Is Everybody Else)
W3C Geolocation API Specification
Geolocation Part II: Building Interactive Maps with Leaflet

One Reply to “Super-simple Geolocation”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.