Back
Aug 8, 2016

How To Add HTML5 Geolocation To Your Web App?

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 get CurrentPosition 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>

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.

Subscribe for the news and updates

More thoughts
Mar 18, 2024Technology
From boring to exciting: turn learning to code into an adventure

Tired of boring programming courses where you're forced to read thick textbooks and write code that's never used? Need a platform that makes learning fun and exciting? Then you're in the right place!

Dec 8, 2022Technology
How to create a route finder on an SVG map

In one of our recent projects, we had an interesting case: the whole application was built around an interactive map for a fairly large shopping mall, and the main goal of the system was to plot the closest route to a user-selected destination.

Aug 27, 2020Technology
5 tips for designing database architecture

Designing database architecture is a challenging task, and it gets even more difficult when your app keeps getting bigger. Here are several tips on how to manage your data structure in a more efficient way.

Jun 25, 2011Technology
Ajax blocks in Django

Quite often we have to write paginated or filtered blocks of information on page. I created a decorator that would automate this process.

Sep 23, 2010Technology
OR and AND without django.db.models.Q

Learn how to use "OR" and "AND" queries efficiently in Django without using database models Q. Enhance your query-building skills. Dive in now.

Sep 23, 2010Technology
Dynamic class generation, QuerySetManager and use_for_related_fields

It appears that not everyone knows that in python you can create classes dynamically without metaclasses. I'll show an example of how to do it.So we've learned how to use custom QuerySet to chain requests:Article.objects.old().public()Now we need to make it work for related objects:user.articles.old().public()This is done using use_for_related_fields, but it needs a little trick.