Background

Geolocation has been a significant feature to track the user’s location. We can represent it on the maps (such as Google Maps, Open Maps) with the help of the coordinates (latitude and longitude) using Javascript. Initially, the user used it to monitor his/her location. However, as the industry grew the uses of geolocation grew too.

Where can you see Geolocation in day to day life?

  1. Uber or any other Taxi service use the GeoLocation of the car to track its location. As a result, they can show the cars around you on their app.
  2. When you use Google Maps to track your location or to find the distance of a place from your position. It uses the GeoLocation to track your position and calculates the distance and time it will take for you to reach the destination.
  3. Tagging locations in the pictures (such as Facebook, Instagram, Snapchat) you have clicked on your phone.

How can you access Geolocation in a Browser?

The Geolocation API allows web applications to access the user’s location if the user desires. Due to privacy issues, the web application prompts the user for permission to report location information.

The Geolocation API gives programs access to the web browser’s geolocation functionality. It tells the program the device’s location on Earth. It is among the most well-supported HTML5 APIs, and about 90 percent of desktop and mobile browsers support it. However, GPS and location inferred from network signals such as WiFi, IP address,  GSM/CDMA cell IDs, RFID, Bluetooth MAC addresses, as well as user input act as the location sources for the location coordinates, which is not guaranteed.

Browsers supporting the GeoLocation API can be found here: http://caniuse.com/#search=geolocation

The Geolocation Object

The geolocation object is accessed using navigator.geolocation object.

You can check the presence of geolocation object using the code below:

if ("geolocation" in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}

The GeoLocation object has three methods:

  • getCurrentPosition
  • watchPosition
  • clearWatch

Getting the current position

You can call the getCurrentPostion() method to get the user’s current position. The getCurrentPosition method takes three arguments:

  • success: A callback function that passes a Position object when geolocation is successful.
  • error: An optional callback function that passes the PositionError object when geolocation fails.
  • options: An optional PositionOptions object that can be used to control several aspects of how the geolocation lookup performs.

When the browser successfully returns the user’s position, properties available within a Position object are:

  1. coords
    • Type: object
    • Details: Includes the coordinates (latitude and longitude) along with heading and speed of the device.
  2. coords.latitude
    • Type: double
    • Details: Mentions the latitude value in decimal and the range is [-90.00, +90.00].
  3. coords.longitude
    • Type: double
    • Details: Mentions the longitude value in decimal and the range is [-180.00, +180.00].
  4. coords.altitude
    • Type: double or NULL
    • Details: [Optional] Defines the altitude or Height in meters above the reference ellipsoid.
  5. coords.accuracy
    • Type: double
    • Details: [Optional] Defines the accuracy of the latitude/longitude in meters.
  6. coords.altitudeAccuracy
    • Type: double or NULL
    • Details: [Optional] Defines the accuracy of the altitude value in meters.
  7. coords.heading

    • Type: double or NULL
    • Details: [Optional] Defines values in degrees of the device’s current direction of movement counting clockwise from true north.
  8. coords.speed

    • Type: double or NULL
    • Details: [Optional] Defines the current ground speed in meters per second of the device.
  9. timestamp
    • Type: DOMTimeStamp
    • Details: Defines the time in timestamp when the location information and the Position object is available.

Example

The example shows how you can use getCurrentPosition method to get the Position object:

<html>

  <head>
    <title>The Position object</title>
    <script>
      if ("geolocation" in navigator) {
        var gps = navigator.geolocation.getCurrentPosition(function(position) {
          for (key in position.coords) {
            document.write(key + ’: ‘+position.coords[key]);
            document.write(‘ < br > ‘);
          }
        });
      }

    </script>
  </head>

  <body> </body>

</html>

When you run the above code, the browser prompts to access your location.

user permission
Latitude Longitude Googe Maps

As a result, if the device supports Geolocation and if the browser can determine your location, the results should resemble the following:

Some of the properties of the Coordinates object are null because it was run using a desktop computer that can’t get some of these properties. While the same script when run on a mobile browser gives following output:

mobile html output

Notice that the mobile browser displays figures for altitude. However, heading and speed are still null because during the page load the device was stationary.

Watching the current position

Sometimes, there is a need to watch the user’s position continuously (Uber, Google Maps). Thus, if the position information updates (either by device movement or if more accurate geo-information arrives), you can set up a callback which will execute. For this, the watchPosition() function is used, which has the same input parameters as getCurrentPosition().

The callback function can execute multiple times. This allows the browser to provide a more accurate location as you move. The device can use different techniques to geolocate you. Similarly, there is an error callback function as well, which is optional. Though, it can repeatedly be called as well.

The main difference between getCurrentPosition and watchPosition is that watchPosition keeps informing user’s position code on change. Thus, it can be used to continuously update the user’s position. This is very useful if the app is tracking a moving device. Whereas getCurrentPosition is returning only once when called.

var watchID = navigator.geolocation.watchPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});

Another difference is that watchPosition method returns a watchID. The clearWatch method requires watchID to stop the position that continually updates.

navigator.geolocation.clearWatch(watchID);

Representing the Coordinates on the Map

We can use Google Maps, or Open Maps to display coordinates (i.e. latitude and longitude) on a visual map using HTML and JavaScript.

<html>

  <head>
    <title>My Location on Map</title>
    <script>
      function geoFindMe() {
        var output = document.getElementById("out");
        if (!navigator.geolocation) {
          output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
          return;
        }

        function success(position) {
          var latitude = position.coords.latitude;
          var longitude = position.coords.longitude;
          output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
          var img = new Image();
          img.src = "http://maps.googleapis.com/maps/api/staticmap?zoom=15&size=512x512&markers=icon:http://pngimages.net/sites/default/files/location-png-image-31558.png|" + latitude + "," + longitude + "";
          output.appendChild(img);
        }

        function error() {
          output.innerHTML = "Unable to retrieve your location";
        }
        output.innerHTML = "<p>Locating…</p>";
        navigator.geolocation.getCurrentPosition(success, error);
      }

    </script>
  </head>

  <body>
    <p> <button onclick="geoFindMe()">Show my location</button> </p>
    <div id="out"></div>
  </body>

</html>

Or you can try the code on here