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:

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().

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

/**

getCurrentPosition() accepts 3 arguments:

a success callback (required), an error callback (optional), and a set of options (optional)

**/

varoptions={

// 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

functionsuccess(pos){

// get longitude and latitude from the position object passed in

varlng=pos.coords.longitude;

varlat=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

functionerror(err){

alert('Error: '+err+' :(');// alert the error message

}

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: and here’s what it looks like in Firefox:

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.

JavaScript

1

2

3

4

5

6

7

8

9

if('geolocation'innavigator){

navigator.geolocation.getCurrentPosition(success);

}

functionsuccess(pos){

varlatitude=pos.coords.latitude;

varlongitude=pos.coords.longitude;

}

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.