The Geolocation API For Dummies, By A Dummy

HTML5 introduced a whole new set of Application Programming Interfaces ( referred to as APIs ). One of them was the Geolocation API.

Despite being part of the HTML5 specification, it’s important to note that the Geolocation API ( as well as most of the other HTML5 APIs ) uses JavaScript. At its most basic, Geolocation gets your ( i.e. your device’s ) current position in the world, in latitude and longitude coordinates. I am by no means an expert at Geolocation, but I’ll try my best to walk you through some of the things that you can do with it and look at a couple of use cases. I’ll also point out some limitations and challenges related to using it.

Here’s a simple example, where we “boot up” Geolocation, get current latitude and longitude coordinates, and output these in an h1 element. Note I’m using jQuery to select the heading from the DOM.

 

<!DOCTYPE html>

<html>

<head>
    <title>Geolocation API Tests</title>
    <meta charset="utf-8">
    <script src="js/jquery/jquery-1.11.1.min.js"></script>
    <script src="js/geolocation.js"></script>
</head>

<body>
    <p>Your current coordinates are</p>
    <h1 id="fw-coords-heading"></h1>
</body>

</html>

 

$(document).ready(function() {

// Boot up Geolocation, and provide a callback function.
navigator.geolocation.getCurrentPosition(outputCoords);

// Defining the callback function.
function outputCoords(position) {
    // Get latitude and longitude values.
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    // Combine latitude and longitude values, put a comma between them. This is the format most external applications/services like to use when used together with Geolocation.
    var coords = lat + ", " + long;
    // Put coordinates into heading.
    $("h1#fw-coords-heading").text(coords);
}
    
});
Result: your current coordinates are outputted.
Result: your coordinates are outputted in the heading.

Geolocation & Google Maps

Of course, there’s only so often you need to output the coordinates themselves. Most people would probably not be very interested in them. However, when implemented with other services, the true power of the coordinates becomes apparent. A popular service to use together with Geolocation is Google Maps.

The next example looks at how we can use the coordinates to show our current position in a Google map, instead of outputting them to a heading.

 

<!DOCTYPE html>

<html>

<head>
    <title>Geolocation API Tests</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script src="js/jquery/jquery-1.11.1.min.js"></script>
    <script src="js/geolocation.js"></script>
</head>

<body>
    <div id="fw-map">
        <!-- We will modify the src of the iframe, using our coords variable -->
        <iframe id="fw-google-map" frameborder="0" src="https://maps.google.com?output=embed"></iframe>
    </div>
</body>

</html>

 

Notice I also set the frameborder to 0 on the iframe. If you do want some borders, you’re free to set it to something else.

 

$(document).ready(function() {
 
// Boot up Geolocation, and provide a callback function.
navigator.geolocation.getCurrentPosition(showMyPosInMap);
 
// Defining the callback function.
function showMyPosInMap(position) {
    // Get latitude and longitude values.
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    // Combine latitude and longitude values, put a comma between them. This is the format most external applications/services like to use when used together with Geolocation.
    var coords = lat + ", " + long;
    // This is where the magic happens. Here, we modify the src of the map to use our current location. Notice that we can also change the zoom level by setting the z parameter. If not using jQuery, use document.getElementByID and setAttribute instead.
    $("#fw-google-map").attr("src", "https://maps.google.com/?q=" + coords + "&z=17&output=embed");
}
    
});
Your coordinates shown in a google map via the Geolocation API
Result: your coordinates are shown in the Google map.

Repeated Position Updates

Showing your current position is all well and good, but what if you’re on the move? You would probably want the position marker to update as you move around. With Geolocation, this is really simple to achieve. All we need to do is replace getCurrentPosition with watchPosition, like this:

 

$(document).ready(function() {
 
// Boot up Geolocation, and provide a callback function. Notice how getCurrentPosition is now replaced with watchPosition.
navigator.geolocation.watchPosition(showMyPosInMap);
 
// Defining the callback function.
function showMyPosInMap(position) {
    // Get latitude and longitude values.
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    // Combine latitude and longitude values, put a comma between them. This is the format most external applications/services like to use when used together with Geolocation.
    var coords = lat + ", " + long;
    // This is where the magic happens. Here, we modify the src of the map to use our current location. Notice that we can also change the zoom level by setting the z parameter. If not using jQuery, use document.getElementByID and setAttribute instead.
    $("#fw-google-map").attr("src", "https://maps.google.com/?q=" + coords + "&z=17&output=embed");
}
    
});

 

Now, every time your physical position changes, your map marker will update. The Geolocation documentation states that the map will scroll as you move. However, as far as I’ve experienced, it simply refreshes (as in, it goes blank for a short time, then displays your updated position). If anybody knows why, do indeed write a comment to let me know.

Handling Errors

So far we’ve seen how Geolocation acts when it actually works. But what about when it doesn’t? Luckily, it has a couple of neat ways to handle errors. There are three main types of errors that can occur when using Geolocation:

  • The user (or browser) denies the use of Geolocation. Geolocation usually (depending on the browser settings) displays a pop up message asking the user for permission to get the current position. If the user denies, Geolocation will not be used. This gives an error code of 1.
  • Geolocation is unavailable. In most occasions, this is due to a lack of Internet connection. This gives an error code of 2.
  • Connection timeout. If retrieving your current position takes too long, geolocation will timeout and stop trying to fetch it. This gives an error code of 3.
  • ( You also have the obvious case where JavaScript is disabled in the browser. In this case, nothing will happen. Without JavaScript enabled, Geolocation won’t be able to handle errors. In fact, it won’t do anything at all. )

So, Geolocation uses three different error codes to identify errors. Since we now know what each of these codes mean, we can provide meaningful feedback to the user if one of these errors occur. We do this by providing another function argument to the navigator.geolocation.watchPosition method, like this:

 

$(document).ready(function() {

// Boot up geolocation, and provide callback functions. The first gets and outputs the coordinates, the second one handles errors that might occur when using Geolocation.
navigator.geolocation.watchPosition(showMyPosInMap, errorHandling);

// Defining the first callback function.
function showMyPosInMap(position) {
    // Get latitude and longitude values
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    // Combine latitude and longitude values, put a comma between them. This is the format most external applications/services like to use when used together with Geolocation.
    var coords = lat + ", " + long;
    // This is where the magic happens. Here, we modify the src of the map to use our current location. Notice that we can also change the zoom level by setting the z parameter. If not using jQuery, use document.getElementByID and setAttribute instead
    $("#fw-google-map").attr("src", "https://maps.google.com/?q=" + coords + "&z=17&output=embed");
}

// Defining the second callback function. This one will handle errors that might occur.
function errorHandling(error) {
    switch(error.code) {
        // Error code 1 - user denies use of geolcation.
        case 1:
            alert("Error code 1: You or your browser denied the site to use geolocation. You might have to check your browser settings.");
            break;
        // Error code 2 - geolocation is unavailable, e.g. due to loss of internet connection.
        case 2:
            alert("Error code 2: Could not retrieve your location. You might have some connection issues. Check your network and try again :)");
            break;
        // Error code 3 - connection timeout.
        case 3:
            alert("Error code 3: Timeout. Connection to geolocation service seems to take longer than usual. Check your Internet connection and try again. If it doesn't work, the fault is probably on Geolocations side. In that case, just wait a while and try again later!");
            break;
    }
}

});

 

Now, if Geolocation detects an error, you will get different types of alert messages, depending on the kind of error. In the example below, I have disabled location tracking in my browser. As a result, this is what the page outputs:

Geolocation error handling. If position tracking is disabled, the user will be alerted.
Result: If you or your browser denies the use of Geolocation, you will be alerted.

For the sake of a good user experience, I don’t encourage frequent use of pop up dialogs like these. The ones I use here are just for illustration purposes. You could instead try creating some status icons, for example red and green lights with text labels next to them or something. I’ll leave that up to your imagination :)

Manually Stop Location Tracking

With Geolocation, you can provide the user with the possibility of manually stopping location tracking.

First you need to put the navigator.geolocation.watchPosition method inside a variable ( I’ve called it watchPos in this case, but call it whatever you want ). Then, create a function where you pass this variable into a clearwatch method. This function can be called on whatever event you want. In the following example, the function is called when the user clicks a button with the id fw­-clearwatch.

 

$(document).ready(function() {

// Boot up geolocation, and provide callback functions. The first gets and outputs the coordinates, the second one handles errors that might occur when using Geolocation. Putting all this into a variable, so we can pass it as an argument into the clearwatch method (see further down)
var watchPos = navigator.geolocation.watchPosition(showMyPosInMap, errorHandling);

// Defining the first callback function.
function showMyPosInMap(position) {
    // Get latitude and longitude values
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    // Combine latitude and longitude values, put a comma between them. This is the format most external applications/services like to use when used together with Geolocation.
    var coords = lat + ", " + long;
    // This is where the magic happens. Here, we modify the src of the map to use our current location. Notice that we can also change the zoom level by setting the z parameter. If not using jQuery, use document.getElementByID and setAttribute instead
    $("#fw-google-map").attr("src", "https://maps.google.com/?q=" + coords + "&z=17&output=embed");
}

// Defining the second callback function. This one will handle errors that might occur.
function errorHandling(error) {
    switch(error.code) {
        // Error code 1 - user denies use of geolcation.
        case 1:
            alert("Error code 1: You or your browser denied the site to use geolocation. You might have to check your browser settings.");
            break;
        // Error code 2 - geolocation is unavailable, e.g. due to loss of internet connection.
        case 2:
            alert("Error code 2: Could not retrieve your location. You might have some connection issues. Check your network and try again :)");
            break;
        // Error code 3 - connection timeout.
        case 3:
            alert("Error code 3: Timeout. Connection to geolocation service seems to take longer than usual. Check your Internet connection and try again. If it doesn't work, the fault is probably on Geolocations side. In that case, just wait a while and try again later!");
            break;
    }
}

// Stop tracking position and alert user.
function stopTrackingPos() {
    // Look at this! Here we pass the watchPos variable as an argument into the clearWatch method. In English: this tells Geolocation to stop (clear) whatever is happening inside the watchPos variable.
    navigator.geolocation.clearWatch(watchPos);
    alert("Position tracking is now disabled");
}

// Calling the stopTrackingPos function on button click.
$("button#fw-clearwatch").click(stopTrackingPos);

});

 

In other words, clicking the button will stop tracking and alert the user that position tracking is disabled.

Position Options

Besides the showMyPosInMap and errorHandling functions, the getCurrentPosition and watchPosition methods accept a third argument, known as the positionOptions object. What this object lets you do is specify certain options for how you want Geolocation to work. You can, for example, set the limit for how much time can pass before the connection to Geolocation times out.

In the following example, we enable the use of GPS technology for GPS enabled devices, we guarantee that the last position we retrieve from Geolocation is never more than one second old, and we give the connection 10 seconds before it times out.

 

$(document).ready(function() {

// Boot up geolocation, and provide callback functions. The first gets and outputs the coordinates, the second one handles errors that might occur when using Geolocation. The third argument contains information about how we want Geolocation to behave. Putting all this into a variable, so we can pass it as an argument into the clearwatch method (see further down)
var watchPos = navigator.geolocation.watchPosition(showMyPosInMap, errorHandling, {
    enableHighAccuracy: true, // Enable high accuracy on GPS enabled devices. Won't affect non-GPS enabled devices.
    maximumAge: 1000, // How long last position can be stored. Sort of the cache window for how long you want to determine/keep users last location. In milliseconds. When 1000, the current position is guaranteed to never be more than a second old. The lower the number, the more frequent updates. Handy when moving around quickly.
    timeout: 10000 // How much time that can pass before the connection to the Geolocation service times out. In milliseconds.
});

// Defining the first callback function.
function showMyPosInMap(position) {
    // Get latitude and longitude values
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    // Combine latitude and longitude values, put a comma between them. This is the format most external applications/services like to use when used together with Geolocation.
    var coords = lat + ", " + long;
    // This is where the magic happens. Here, we modify the src of the map to use our current location. Notice that we can also change the zoom level by setting the z parameter. If not using jQuery, use document.getElementByID and setAttribute instead
    $("#fw-google-map").attr("src", "https://maps.google.com/?q=" + coords + "&z=17&output=embed");
}

// Defining the second callback function. This one will handle errors that might occur.
function errorHandling(error) {
    switch(error.code) {
        // Error code 1 - user denies use of geolcation.
        case 1:
            alert("Error code 1: You or your browser denied the site to use geolocation. You might have to check your browser settings.");
            break;
        // Error code 2 - geolocation is unavailable, e.g. due to loss of internet connection.
        case 2:
            alert("Error code 2: Could not retrieve your location. You might have some connection issues. Check your network and try again :)");
            break;
        // Error code 3 - connection timeout.
        case 3:
            alert("Error code 3: Timeout. Connection to geolocation service seems to take longer than usual. Check your Internet connection and try again. If it doesn't work, the fault is probably on Geolocations side. In that case, just wait a while and try again later!");
            break;
    }
}

// Stop tracking position and alert user.
function stopTrackingPos() {
    // Look at this! Here we pass the watchPos variable as an argument into the clearWatch method. In English: this tells Geolocation to stop (clear) whatever is happening inside the watchPos variable.
    navigator.geolocation.clearWatch(watchPos);
    alert("Position tracking is now disabled");
}

// Calling the stopTrackingPos function on button click.
$("button#fw-clearwatch").click(stopTrackingPos);

});

 

Limitations and Challenges With Geolocation

An obvious thing to be aware of is that Geolocation requires you to have JavaScript enabled in your browser. Some might disable JavaScript in their browser in order to increase performance or save battery life. This is particularly true for mobile devices. Thus, you should make sure your web site or application works even if Geolocation is not available. Geolocation also requires an Internet connection. As a result, Geolocation can not really be used in offline-only web applications.

By default, browsers will ask for permission to use Geolocation, through a pop­up dialog. Some might find this annoying, especially if they have no interest in using it anyway. For this reason, I would not recommend excessive use of Geolocation.

With location tracking comes a set of privacy concerns. Since Geolocation reveals your location, it should not be used without your explicit permission. By default, browsers will ask for permission to use Geolocation through a pop­up dialog, which is a decent measure against unauthorized use. However, users have the opportunity to disable this dialog and let the browser either automatically reject or accept use of Geolocation. This can be important to keep in mind when developing your web site or application.

Geolocation is also able to store your location information beyond the length of your browsing session. In other words, a web site can store your location even after you’ve closed the browser. The documentation states that this stored information must be revocable by you at any time, preferably through an easy to use graphical interface. The documentation also clearly states that location information must never be used for anything other than the intended and obvious (obvious to you, the user) purpose. When the intended purpose is completed, the location information must be disposed of, unless the user explicitly says otherwise. It’s also important for web sites and applications to make sure that your location is not available to unauthorized third parties.

Finally, the documentation provides a set of rules for how web sites and applications must inform the user about the use of Geolocation. They must clearly state the following to the user:

  • The fact that they are collecting location data.
  • The purpose of the collection.
  • How long the data is retained.
  • How the data is secured.
  • How the data is shared if it is shared.
  • How users may access, update and delete the data.
  • Any other choices that the user has with respect to the data.

This might sound like it could make for a messy user interface, but the documentation does not specify how this information should appear. For example, if you’re running a store and using Geolocation so that your customers can find the nearest store, your site might say something like “Find nearest store.” As far as I can tell from the documentation, that would be good enough to describe the purpose of your location collection (point 2 in the list). So it should be possible to design a non-messy interface even when fullfilling all these points.

Final Example

I hope this has made Geolocation a bit less scary, and that you can now go and do something awesome with it. I want to end this post with a more flushed out example, where all the functionalities mentioned above are used simultaneously. Here, your position will be tracked continuously. The position itself is available in a text box (as coordinates) as well as in a Google map. You have the ability to both start and stop tracking manually. Errors like timeout and connection issues will be handled with appropriate messages through alert windows (I still encourage you to find better ways of alerting users). Links to online demo and source files are available below the image.

An example implementation of Geolocation and Google Maps.
Final example, using all the techniques mentioned in this post.

Online Demo Source Files