How To Add HTML5 Geolocation To Your Web App?

, , django, javascript, html5

Introduction

Today an increasing number of applications use users’ geolocation data. These include navigators and maps, taxi and weather-forecast services, various rental and booking services like Uber or Airbnb, even messengers – all of them are using geolocation to provide more convenient, friendly and fast services. Running a weather forecast app, the user most probably wants to get information about weather in his current location rather than somewhere in Madison, Wisconsin, USA (apologies if you are reading this article from there). Geolocation saves time in such cases by detecting the current location automatically without any additional user input or scrolling long lists in an effort to find necessary city.

In this article I will describe how to ​add geolocation to website so then you can easily implement it. As an example we are going to create small web app which will be able to calculate the shortest route between detected user’s location (point A) and predefined destination (point B) using Google Maps API. Let’s take our company office address as point B for this example (welcome for a cup of coffee).

Geolocation in HTML5

In an age of gadgets when many of them have GSM/WIFI/GPS modules it became important and necessary to design kind of secure interface which allows web application to define user location on client’s side. The W3C created Geolocation Working Group for this task and the solution was found! This is html5 geolocation service which is supported by all modern web browsers (even IE!)

IEEdgeFirefoxSafariChromeOperaSafari iOSAndroid Browser
11+13+35+9.1+29+38+9.3+4.3+

HTML5 geolocation API

First of all we need to connect navigator.geolocation module to use all methods described below.

Method getCurrentPosition()

This method is used to define the current location of a user. There are three arguments we need to pass to the method. The first one is a function where the method will save geo tag, the second one is an error-handling function. Due to security reasons we can’t start defining a user’s location without their approval. If the user denies the request we can use their IP, but maximum information we can get this way is their country or city in best case. Not very accurate way. The third argument can be PositionOptions but we will talk later about this.

function showPosition(position) {
    console.log("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude)
}
function showError(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation.";
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable.";
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out.";
            break;
        case error.UNKNOWN_ERR:
            x.innerHTML = "An unknown error occurred.";
            break;
    }
}
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition)
} else {
    console.log("Geolocation API doesn't supported.")
}

First of all in the example we checked whether the browser supports html5 geolocation. If it does then the method requests current location otherwise it logs an error “Geolocation API is not supported”. If you need to use geolocation in browsers which don’t support this API you can check geolocation javascript library provided by Google.

WatchPosition()

What if we need to track user’s movement? It is considered bad manners to run getCurrentPosition continuously, the best way is to use watchPosition() instead. This method can automatically track changes of position and run relevant callback function received in parameter (along with PositonOptions).

PositionOptions

We mentioned third optional parameter PositionOption, now let’s explore it. PositionOptions has three optional properties some of them are predefined.

  • enableHighAccuracy – if set to “true” this property allows to locate user more accurately but it requires more time and battery power of device. “False” by default.
  • timeout – number of milliseconds the application waits for getting user’s location until shows the exception error. Counting starts right after user approval of the geolocation request. No default value.
  • maximumAge – caching time in milliseconds, default 0. This parameter allows application to keep last geolocation data for defined number of milliseconds and use it as current position. As the geolocation is an energy consuming procedure the last geolocation request result is cached and will be immediately returned if within the caching period.

How to add geolocation to website.

It’s time to implement all abovementioned in some example. As promised we will create custom web app with html5 geolocation to calculate the shortest route between your current location and predefined point. It’s better if we will also handle and show exceptions to be aware of errors.

Web page layout

To build our web app with integrated geolocation functionality we need to choose a tool for showing the map and geotags, calculate and draw the route. We will use Google Maps as this is one of the best services with necessary functions, API, manuals and examples for developers.

Below there is a layout for simple webpage with Google Map.

<!DOCTYPE html>
<html>
<head>
    <title>How to get to our office?</title>
</head>
<body>
<style type="text/css">
    html, body {
        margin: 0;
    }
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
    }
</style>
<div id="map"></div>
<script>
    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 3,
            center: {lat: 0, lng: 0}
        });
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&quot; async defer></script>
</body>
</html>

Notice: the purpose of this article is not to describe Google Maps API, you can find all necessary information and manuals on its web page.

Locating and displaying the position

First let’s display our office location (the predefined destination point) using google.maps.marker.

<!DOCTYPE html>
<html>
<head>
    <title>How to get to our office?</title>
</head>
<body>
<style type="text/css">
    html, body {
        margin: 0;
    }
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
    }
</style>
<div id="map"></div>
<script>
    function initMap() {
        var officePos = {lat: 50.438284, lng: 30.515339};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 17,
            center: officePos
        });
        var markerOffice = new google.maps.Marker({
            position: officePos,
            map: map,
            label: 'A'
        });
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&quot; async defer></script>
</body>
</html>

Now it’s time to request and show the user’s location. To implement the ​html5 geolocation api it’s not necessary to link any external additional libraries, we will just use method getCurrentPosition passing relevant callback to it.

<!DOCTYPE html>
<html>
<head>
    <title>How to get to our office?</title>
</head>
<body>
<style type="text/css">
    html, body {
        margin: 0;
    }
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
    }
</style>
<div id="map"></div>
<script>
    function initMap() {
        var bounds = new google.maps.LatLngBounds();
        var officePos = {lat: 50.438284, lng: 30.515339};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 15,
            center: officePos
        });
        var markerOffice = new google.maps.Marker({
            position: officePos,
            map: map,
            label: 'A'
        });
        bounds.extend(markerOffice.position);

        navigator.geolocation.getCurrentPosition(
            function(position) {
                var currentPos = {lat: position.coords.latitude, lng: position.coords.longitude};
                var markerCurreintPos = new google.maps.Marker({
                    position: currentPos,
                    map: map,
                    label: 'B'
                });
                bounds.extend(markerCurreintPos.position);
                map.fitBounds(bounds);
                map.panToBounds(bounds);
            }
        )
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&quot; async defer></script>
</body>
</html>

Calculating the route.

Having displayed both points on the map we can map a route between them. For calculating the route we will use google.maps.DirectionService and google.maps.DirectionsRender for drawing.

<!DOCTYPE html>
<html>
<head>
    <title>How to get to our office?</title>
</head>
<body>
<style type="text/css">
    html, body {
        margin: 0;
    }
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
    }
</style>
<div id="map"></div>
<script>
    function handleNotifications(map, pos, msg) {
        var infoWindow = new google.maps.InfoWindow({map: map});
        infoWindow.setPosition(pos);
        infoWindow.setContent(msg);
    }
    function humanizeGeolocationErrorMsg(error) {
        switch(error.code) {
            case error.PERMISSION_DENIED:
                return "User denied the request for Geolocation.";
            case error.POSITION_UNAVAILABLE:
                return "Location information is unavailable.";
            case error.TIMEOUT:
                return "The request to get user location timed out.";
            case error.UNKNOWN_ERROR:
                return "An unknown error occurred."
        }
    }
    function initMap() {
        var officePos = {lat: 50.438284, lng: 30.515339};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 15,
            center: officePos
        });

        var directionsService = new google.maps.DirectionsService;
        var directionsRenderer = new google.maps.DirectionsRenderer({map: map});
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function (position) {
                    var currentPos = {lat: position.coords.latitude, lng: position.coords.longitude};

                    directionsService.route({
                        origin: currentPos,
                        destination: officePos,
                        travelMode: google.maps.TravelMode.DRIVING
                    }, function(response, status) {
                        if (status === google.maps.DirectionsStatus.OK) {
                            directionsRenderer.setDirections(response);
                        } else {
                            handleNotifications(map, map.getCenter(), 'Directions request failed!');
                        }
                    });
                }, function(error) {
                    handleNotifications(map, map.getCenter(), humanizeGeolocationErrorMsg(error));
                }
            )
        } else {
            handleNotifications(map, map.getCenter(), "Your browser doesn't support html5 geolocation");
        }
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&quot; async defer></script>
</body>
</html>

The final html5 geolocation example, you can see here.

Conclusion

Now we know how to add html5 geolocation to web app. HTML5 geolocation service is a simple but convenient way to get user geolocation data by using unified approach while ensuring user privacy.

contact us right now