Getting a User Location in HTML

Javascript is a great language for the web; we can perform many tasks using it, making the web more dynamic. We can also use the scripting language to collect the user location or track the user. The user location that we collect can be used for tracking our customers, better mapping facility, recommending users something based on their location, etc. A simple application of location-based services is Food ordering Services, which get the user location and suggest nearby restaurants.

In this tutorial, we will learn about Javascript’s geolocation API and see how to use it to request users for their location information.

Introduction

The Javascript Geolocation API provides a great and standard way to request a user for its location. The location provided by the user can be determined using GPS, WIFI, IP Geolocation, etc., which depends on the device used by the user. To protect the user’s privacy, it will first ask for permission to locate the device, and if the user grants permission, we can locate the device.

Sources of Location

The Geolocation API of Javascript uses some sources like GPS, WiFi, IP Geolocation to get the location of a device. Each of these methods is different in its accuracy. Let us see more about these methods.

  • Global Positioning System(GPS): This is the most accurate system for locating a device. Many GPS devices have an accuracy of about 1 foot. These systems are available on most of the latest mobile phones.
  • WiFi: WiFi is another good method of locating a device. It is supported by most of the modern and old mobile devices. Rather it has an accuracy less than GPS, but it is a useful way to locate users in non GPS devices.
  • IP Geolocation: This is the last method and the least accurate method for locating a device. This method is used if a device does not have the support of both GPS and WiFi.

The Browser will use any of this method depending on the device for locating a user.

Javascript Geolocation API

In Javascript, we have a navigator.geolocation object, which is used to locate devices. This object provides the below methods for working with the device location.

  • getCurrentPosition(): This method is used to get the user’s current location. This method will return an object which contains pieces of information like latitude, longitude, accuracy in meters.
  • watchPosition(): This method will listen to the user for any location changes, and if there is any location change, it will call a function.
  • clearWatch(): This method is used to remove any handler attached to a watchPosition() call, so the user will no longer be tracked by the site when the location of the user changes.

Before using any of these methods for finding the location, the site must have to request the user for permission to locate the device.

Getting the Current Position

The main motive of this post is to get the user location using javascript. Now we are going to look at how to achieve that. To get the user’s current location, we need to use the getCurrentPosition() method of the Javascript geolocation object. Because of the user’s privacy, this method will ask the user for permission to get the location, and if the permission is granted, we can get the location using Javascript. The getCurrentPosition() method has two parameters, the first one is the returned coordinate object and the second one is the error object if there is any. See the below code for illustration.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="location"></div>
    <script>
      var div  = document.getElementById("location");
      function getLocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
          div.innerHTML = "The Browser Does not Support Geolocation";
        }
      }

      function showPosition(position) {
        div.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
      }

      function showError(error) {
        if(error.PERMISSION_DENIED){
            div.innerHTML = "The User have denied the request for Geolocation.";
        }
      }
      getLocation();
    </script>
  </body>
</html>

If we run the above code using the run button present at the top menu of the code block, We will be asked for permission by the site that the site wants our location. If we click the allow button, the site can access our location, and the showPosition() function will be called, and if we click on the block button, the site can’t access our location showError() function will be called.

If you click the allow button while running the above code, then your current position’s longitude and latitude will be displayed. The coords object of the getPosition() method also provides many other details. Below is a list of all the values provided by the coords object.

  • coords.latitude: This will return the latitude of the current position
  • coords.longitude: This will return the longitude of the current position
  • coords.accuracy: This contained the value of the accuracy of the position coordinates.
  • coords.altitude: It will return the altitude of the user device if the device supports the functionality. The altitude is the mean height of the device from the sea level.
  • coords.altitudeAccuracy: This will return the accuracy of the altitude.
  • coords.heading: This will return the device’s degree from the north in a clockwise direction(Not supported by all devices).
  • Timestamp: This will return the date/time of the response if available.

We have got the current position of the user but we can also track the user by watching their position.

Watching the Users Position

We can use the watchPosition() method of the geolocation object to tracking the users and get updated when the location changes. The watchPosition() method is also similar to getCurrentPosition() method of the geolocation object. See the below code for illustration.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="location"></div>
    <script>
      var div  = document.getElementById("location");
      function getLocation() {
        if (navigator.geolocation) {
          navigator.geolocation.watchPosition(showPosition);
        } else {
          div.innerHTML = "The Browser Does not Support Geolocation";
        }
      }

      function showPosition(position) {
        div.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
      }
      getLocation();
    </script>
  </body>
</html>

In the above code block, we used the watchPosition() method of the geolocation object for tracking the user location. The location of the user will be updated every time the user will change its location.

Plotting the User Location on Google Maps

We can also display the user location in a map by using the API provided by google maps. To use google maps in our code, we need to get an API Key from Google. After getting an API Key, we can easily use the Google Maps API to plot the map with the user location on the map. See the below code for illustration.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="location"></div>
    <script>
      var div = document.getElementById("location");

      function getLocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition, console.log);
        } else {
          div.innerHTML = "The Browser Does not Support Geolocation";
        }
      }

      function showPosition(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        // You need to enter your API Key here
        var api_key = "";
        var img_url = `https://maps.googleapis.com/maps/api/staticmap?center=${lat},${lon}&zoom=14&size=400x300&sensor=false&key=${api_key}`;
        div.innerHTML = `<img src='${img_url}'>`;
      }
      getLocation();
    </script>
  </body>
</html>

In the above code block, we use the google map API to get an image URL of the map with the user’s location. In the google map API URL, we have given three values, i.e., the longitude, latitude, and the API Key. Then we create a <img> tag and place the image URL in the src attribute of the tag.

Conclusion

In this tutorial, we learned how to use the javascript’s geolocation API to get a user location or track the user using the watchPosition() method. We have also learned how to plot the user’s location in Google Maps using the Google Maps API. You may also want to see our step by step guide on using SVG images on the Web, which compares all the method of inserting SVG images in a webpage.

Similar Posts

Loading comments...