11 - HTML5 Geolocation

HTML5 Geolocation API offers methods to track the location of the user. You can do a lot of location-aware things using geolocation information. For example, business stores can help viewers to find their shops near the viewers. However, as the geolocation information is really private, you will be able to retrieve the position information of the user only if the user approves.

There are mainly three different techniques to track the location of the user. You can find the location by finding the IP address of the user on the Internet. You can also use 3G triangulation technique where the user’s location is triangulated by finding the nearest cell tower your cell phone is communicating to. The third technique is the most accurate one that uses a dedicated GPS hardware on the device to calculate the latitude and longitude information sent by satellites. When you try to run the following examples from a computer, the information might not be that accurate as it does not have a GPS hardware. But if you try it from a smart phone, the information will be more accurate.

Different Methods

HTML5 Geolocation API offers three different methods: getCurrentPosition(), watchPosition() and clearWatch(). You can use the getCurrentPosition() method to find the position of the user for a specific point of time. If you want to track the position of the user over a period of time as the user moves, then you can use the watchPosition() method and it will return a number. You should store this number somewhere and call the clearWatch() method if you want to stop tracking the location passing the number.

The syntax of getCurrentPosition() and watchPosition() methods are the same. The syntax is

getCurrentPosition (onSuccess, onError, {properties});

watchPosition (onSuccess, onError, {properties});

Here, onSuccess is a callback function that will be called once the location is retrieved successfully, onError is a callback function that will be called if the location could not be retrieved by any chance and properties is a JSON object that specifies a number of attributes including enableHighAccuracy, timeout and maximumAge. The first parameter is a required parameter and second and third parameters are optional parameters.

The onSuccess callback function returns a Position object with two properties: coords and timestamp. The timestamp returns the date and time when the location was retrieved. The coords object has properties like latitude, longitude, altitude, accuracy, altitudeAccuracy, heading and speed. The onError callback function returns a PositionError object with two properties: code and message. The value of the code property could be PERMISSION_DENIED (1) if the user denies to share the information, POSITION_UNAVAILABLE (2) if the position could not be retrieved or TIMEOUT (3) if it takes too long to retrieve the information.

The JSON object can specify three attributes: enableHighAccuracy, timeout and maximumAge. You can get the most accurate position possible by setting the value of enableHighAccuracy to true. The timeout is an integer value that indicates the time allowed in milliseconds for obtaining the position information and if that time is over, the TIMEOUT error will be returned. The maximumAge is an integer value indicating the maximum age of cached position information. For example, if you set the value of maximumAge to 5000, if you try to get the location on 5:00 AM and 5:03 AM, the device will not try to recalculate the position. Bothe the information will be the same. So, set the value of maximumAge considering how much accuracy your application needs.

A Basic Example using getCurrentPosition()

Let’s try to implement a basic example using the getCurrentPosition() method and passing only the one required parameter. Not every browser support HTML5 Geolocation. So it is a good programming practice to check whether the browser supports geolocation. The navigator object contains information about the browser and geolocation returns a geolocation object.

Sample Code:

<!DOCTYPE html>
<html>
 <head>
  <title>Geolocation getCurrentPosition</title>
  <script>
   function getLocation()
   {
   if(navigator.geolocation)
   {
   navigator.geolocation.getCurrentPosition(position_success);
   }
   else
   {
    document.getElementById("result").innerHTML = "Your bowser does not support Geolocation";
   }
   }
   function position_success(position)
   {
   document.getElementById("result").innerHTML = "<b>Latitude:</b> " + position.coords.latitude + "<br /> <b>Longitude: </b>" + position.coords.longitude; 
   }
  </script>
 </head>
 <body>
  <button id="location" onclick="getLocation();">Find Location</button><br /><br />
  <div id="result"></div>
 </body>
</html>

Make sure that you access the file from a server. You can save this file in C:\inetpub\wwwroot folder or xampp\htdocs folder and access it as localhost/filename.html. When you try to access this site for the first time, you will find a message like this:

      HTML5_getcurrentposition

The location information will be retrieved only if you click the Allow button. Once you click the Allow button, you will get the following output.

       HTML5 getcurrentposition example

I have hidden the value. However, you will get the correct value when you try this.

An Advanced Example using watchPosition()

Let’s try to implement a more advanced example using the watchPosition() method and passing all the parameters. We are going to do error handling in this example.

Sample Code:

<!DOCTYPE html>
<html>
 <head>
  <title>Geolocation watchPosition</title>
  <script>
   function getLocation()
   {
    if(navigator.geolocation)
    {
     navigator.geolocation.watchPosition(position_success, position_error, { maximumAge: 4000,                                             timeout: 5000,
                                          enableHighAccuracy: true  }
     );
    }
    else
    {
     document.getElementById("result").innerHTML = "Your bowser does not support Geolocation";
    }
    }
    function position_success(position)
    {
     document.getElementById("result").innerHTML = "<b>Latitude:</b> " + position.coords.latitude + "<br><b>Longitude:</b> " + position.coords.longitude; 
    }
  function position_error(error)
   {
    alert("Error Code: " + error.code + " Message: " + error.message);
   }
   function stopTracking()
   {
   navigator.geolocation.clearWatch(myWatch);
   }
  </script>
 </head>
 <body>
   <button id="location" onclick="getLocation();">Find Location</button>
   <button id="stop" onclick="stopTracking();">Stop Tracking</button><br /><br />
   <div id="result"></div>
  </body>
</html>

Click the Block button and you will find a message like this:

          HTML5 watchposition example

You can make the error handling more detailed if you want. Remove the line of code in the position_error function and add the following lines of code.

var message;
switch(error.code)
{
case 1:
  message = "User denies permission to access his information";
  break;
case 2: 
    message = "Position could not be retrieved";
    break;
case 3:
    message = "Geolocation timed out";
    break;
default:
    message: "Position information is not available";
    break;
}
alert(message);

Now if you click the Block button, you will get a message like this:

        HTML5 watchposition example 2

Display a Map using Geolocation

Just displaying latitude and longitude might not be helpful for users. You can use the latitude and longitude information to display the location information in a map. You can use a map service to display the information and a popular map service is Google Maps API.

Sample Code:

<!DOCTYPE html>
<html>
 <head>
  <title>Geolocation Map</title>
  <script src="http://maps.googleapis.com/maps/api/js"></script>
  <script>
   function getLocation()
   {
    if(navigator.geolocation)
    {
     navigator.geolocation.getCurrentPosition(position_success, position_error, { 
     maximumAge: 10000,
                                    timeout: 20000,
                                enableHighAccuracy: true  }
    );
    }
    else
    {
     document.getElementById("result").innerHTML = "Your bowser does not support Geolocation";
    }
   }
   function position_success(position)
   {
    //var myPoint = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    var myPoint = new google.maps.LatLng(40.79,-73.95);
    var mapProp = {
     center:myPoint,
     zoom:9,
     mapTypeId:google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("mapArea"),mapProp);
    var marker = new google.maps.Marker({
    position:myPoint,
    });
   marker.setMap(map);
   }
   function position_error(error)
   {
    var message;
    switch(error.code)
    {
     case 1:
     message = "User denies permission to access his information";
     break;
     case 2: 
     message = "Position could not be retrieved";
    break;
     case 3:
    message = "Geolocation timed out";
    break;
     default:
    message: "Position information is not available";
    break;
    }
     alert(message);
   }
  </script>
 </head>
 <body>
  <button id="location" onclick="getLocation();">Find Location</button><br /><br />
  <div id="mapArea" style="height:500px;width:500px;"></div><br />
  <div id="result"></div>
 </body>
</html>

Output:

      HTML5 display map example

Summary

In this section, we have seen how to use getCurrentPosition() and watchPosition() methods to track the location of the user and also how to handle errors. We could also use geolocation to display the details in a map. 

Like us on Facebook