Working With Geolocation API

Here we will learn how to work with the Geolocation API.

Geolocation API

Introduction: The Geolocation API allows a website to retrieve the current geographical location of a user. This API allows you to create an application that helps the user to reach a target location from their current location. For example, we can have a map application that gives directions to a target location. The Geolocation API retrieves location from a Device IP Address, the nearest mobile phone towers and GPS. Geolocation is the most beneficial with applications for mobile devices. For example, the Geolocation API keeps updating their location when they are in travel.

The following method determines the user's location:

  • getCurrentPosition(CallbackFunction,ErrorHandler,Options): retrieves the user's current geographical location as a set of coordinates.
CallBackFunction Defined by the developer to retrieve the current location.
ErrorHandler This is an optional parameter to specify the name of the function that is called when an error occurs when retrieving the location of a user. This method is called with the PositionError object that stores the returned error information.
Options This parameter specifies a set of options such as timeout for retrieving location information.

The getCurrentPosition() method calls a callback function that takes the position object as an argument and this object specifies the current geographical location as coordinates.

The Position object returns the two properties coords and timestamp. The coords property returns the various attributes as given below:

  • coords.latitude: Specifies the latitude as a decimal number.
  • cords.longitude: Specifies the longitude as a decimal number.
  • coords.accuracy: Specifies the accuracy of position.
  • coords.altitude: Specifies the altitude in meters above sea level.
  • coords.altitudeAccuracy: Specifies the accuracy of altitude.
  • coords.heading: Specifies a heading as degrees clockwise from North
  • coords.speed: Specifies the speed in meters per second.

Code Example

  1. <html>  
  2.     <body>  
  3.       
  4.     <input type="Button" value="Get Location" onclick="getLocation()"/>  
  5.     <div id="result">You are at : </div>  
  6.     <SCRIPT>  
  7.        var gLocation=document.getElementById("result");  
  8.        function getLocation()  
  9.        {  
  10.           //Check whether browser is supporting geolocation or not.   
  11.           if(navigator.geolocation)  
  12.           {  
  13.              navigator.geolocation.getCurrentPosition(getPosition);  
  14.           }  
  15.           else  
  16.           {  
  17.              gLocation.innerHTML="Geolocation is not supported by this browser.";  
  18.           }  
  19.           function getPosition()  
  20.           {  
  21.              gLocation.innerHTML="Latitude : "+position.coords.latitude+" Longitude : "+position.coords.longitude;  
  22.           }  
  23.        }  
  24.     </SCRIPT>  
  25.     </body>  
  26. </html> 

Note: Due to your network security firewall you may not get latitude and longitude.

watchPosition(): This method returns the current location of a user and continuously updates the location while the user is moving. If you want to stop tracking the user's current location then you can call the clearWatch() method.

Code Example

  1. <html>  
  2.     <body>  
  3.       
  4.     <input type="Button" value="Watch Location" onclick="getLocation()"/>  
  5.         <input type="Button" value="Stop watching" onclick="stopWatch()"/>  
  6.     <div id="result">You are at : </div>  
  7.     <SCRIPT>  
  8.         var watchId;  
  9.         var geoLoc;  
  10.         var gLocation = document.getElementById("result");  
  11.         function getLocation() {  
  12.             //Check whether browser is supporting geolocation or not.   
  13.             if (navigator.geolocation) {  
  14.                 var options = { timeout: 60000 };  
  15.                 geoLoc = navigator.geolocation;  
  16.   
  17.                 watchId = geoLocwatchPosition(getPosition, options);  
  18.             }  
  19.             else {  
  20.                 gLocation.innerHTML = "Geolocation is not supported by this browser.";  
  21.             }  
  22.             function getPosition() {  
  23.                 gLocation.innerHTML = "Latitude : " + position.coords.latitude + " Longitude : " + position.coords.longitude;  
  24.             }  
  25.         }  
  26.         function stopWatch() {  
  27.             geoLoc.clearWatch(watchID);  
  28.         }  
  29.   
  30.     </SCRIPT>  
  31.     </body>  
  32. </html> 

Error Handling: There might be a situation when you get error messages due to an applied restriction on location. An error may occur when the device goes out of the coverage area or the network connection times out. We need to consider all the possible causes of the error that can appear in the application. We can use the getCurrentPosition() method that has a second parameter as the error handler function. This function can handle the following errors:

POSITION_UNAVAILIBLE Occurs when the location of the device cannot be determined.
TIMEOUT Occurs when the method was unable to retrieve the location information within the specified maximum timeout interval.
PERMISSION_DENIED Occurs when the method failed to retrieve the location of the device because the application does not have permission to use the Location Service.
UNKNOWN_ERROR Occurs when an unknown or undefined error occurs

Code Example

  1. <html>  
  2.     <body>  
  3.       
  4.     <input type="Button" value="Watch Location" onclick="getLocation()"/>  
  5.         <input type="Button" value="Stop watching" onclick="stopWatch()"/>  
  6.     <div id="result">You are at : </div>  
  7.     <SCRIPT>  
  8.         var watchId;  
  9.         var geoLoc;  
  10.         var gLocation = document.getElementById("result");  
  11.         function getLocation() {  
  12.             //Check whether browser supporting geolocation or not.   
  13.             if (navigator.geolocation) {  
  14.                 var options = { timeout: 60000 };  
  15.                 geoLoc = navigator.geolocation;  
  16.   
  17.                 watchId = geoLoc.watchPosition(getPosition, options);  
  18.             }  
  19.             else {  
  20.                 gLocation.innerHTML = "Geolocation is not supported by this browser.";  
  21.             }  
  22.               
  23.         }  
  24.         function getPosition() {  
  25.                 gLocation.innerHTML = "Latitude : " + position.coords.latitude + " Longitude : " + position.coords.longitude;  
  26.             }  
  27.         function errorHandler(PositionError) {  
  28.             if (PositionError.code == PositionError.PERMISSION_DENIED) {  
  29.                 alert("Error: Access is denied!");  
  30.             } else if (PositionError.code == PositionError.TIMEOUT) {  
  31.                 alert("Error: Request Timeout !");  
  32.             }  
  33.             else if (PositionError.code == PositionError.POSITION_UNAVAILIBLE) {  
  34.                 alert("Error: User's location is not availible !");  
  35.             }            
  36.             else if(PositionError.code == PositionError.UNKNOWN_ERROR){  
  37.                 alert("Error: Unknown Error !");  
  38.             }  
  39.         }  
  40.         function stopWatch() {  
  41.             geoLoc.clearWatch(watchID);  
  42.         }  
  43.   
  44.     </SCRIPT>  
  45.     </body>  
  46. </html>