Geolocation In HTML5

Understand term Geolocation

 
The Geolocation API of HTML5 helps to identify the user’s location. That can be used to provide location-specific information. For privacy reasons, the user is asked for permission to report location information. The HTML 5 geolocation API provides the geographical location of the user. There are many techniques used to identify the location of the user. A desktop browser generally uses WiFi or IP based positioning techniques whereas a mobile browser uses cell triangulation, GPS and A-GPS (Assistive GPS) to triangulate between mobile phone towers and public masts to determine the location and WiFi-based positioning techniques, and so on.
 
The Geolocation API will use any of these techniques to identify the user’s location. The Geolocation API protects the user’s privacy by mandating that the user's permission should be sought and obtained before sending the location information of the user to any website. So the user will be prompted with a popover or dialog requesting for the user’s permission to share the location information. The user can accept or deny the request.
 
 

Geolocation Object 

 
The Geolocation API is published through the navigator.geolocation object. If this object is present then the geolocation service works.
 
var geolocation=navigator.geolocation;
 
A geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device.
 

Browser Compatibility

 
The geolocation property of the global navigator object helps in detecting the browser support for the Geolocation API.
  1. If (navigator.geolocation)  
  2. {  
  3. //Get the user’s current position  
  4. }  
  5. Else  
  6. {  
  7. Alert (‘Geolocation is not supported in your browser’);  

Geolocation Methods

 
The getCurrentPosition method gets the current location of the user. It takes two arguments in the form of callbacks, one is the Success Callback function. This callback function is invoked only when the user accepts to share the location information and the location data is successfully fetched by the browser. The location data will be available as a position object. The success callback takes a Position object as an argument. It optionally takes a third argument in the form of a PositionOptions object. the second one is the Error Callback function for a failed location query.
 

Properties of Position object

 
Property Value Unit
Coords.latitude Double degrees
Coords.langitude Double degrees
Coords.altitude Double or null meters
Coords.accuracy Double meters
Coords.altitudeAccuracy Double or null meters
Coords.heading Double or null Degrees clockwise
Coords.speed Double or null Meters/second
timeStamp DOMTimeStamp Like the Date object
 
The coords object has the following properties:
  • Latitude, longitude: Geographic coordinates in decimal degrees
  • Accuracy: Accuracy level of the latitude and longitude coordinates in meters. Less accuracy when the number is big.
  • Altitude: Height of the position above the sea level in meters
  • AltitudeAccuracy: Denotes how far off the altitude position could be from the actual attitude value obtained in meters. The larger the number the lesser the accuracy.
  • Heading: Provides 360 degree heading information
  • Speed: Indicates relative speed in Meters Per Second.
Syntax of getCurrentPosition ( ) method
 
getCurrentPosition (showLocation, ErrorHandler, options);
 
Let define parameters of getCurrentPosition
 
showLocation: This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object that stores the returned location information.
 
ErrorHandler: This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the Position Error object that stores the returned error information.
 
Options: This optional parameter specifies a set of options for retrieving the location information. We can specify:
  • Accuracy of the returned location information
  • Timeout for retrieving the location information
  • Use of cached location information.

     Code
    1. <!DOCTYPE HTML>  
    2. <head>  
    3.    <script type="text/JavaScript">  
    4.       function showLocation(position) {       
    5.           var latitude = position.coords.latitude;        
    6.           var longitude = position.coords.longitude;        
    7.           alert("Latitude : " + latitude + " Longitude: " + longitude);        
    8.       }              
    9.       function errorHandler(err) {        
    10.           if (err.code == 1) {        
    11.               alert("Error: Access is denied!");        
    12.           }   
    13.       else if (err.code == 2) {        
    14.               alert("Error: Position is unavailable!");       
    15.           }        
    16.       }        
    17.       function getLocation() {              
    18.           if (navigator.geolocation) {  
    19.               var options = { timeout: 60000 };        
    20.               navigator.geolocation.getCurrentPosition(showLocation, errorHandler,        
    21.       options);        
    22.           }        
    23.           Else        
    24.           {        
    25.               alert("Geolocation is not supported by browser");        
    26.           }       
    27.       }        
    28.    </script>  
    29. </head>  
    30. <html>  
    31.    <body>  
    32.       <form>  
    33.          <input type="button" onclick="getLocation();" value="Get Location"/>  
    34.       </form>  
    35.    </body>  
    36. </html> 
    When you write, save and open this web page in your browser, it gives output like this;
     
     
     
watchPosition: This method retrieves your current location periodically. The location information is returned in a Position object. Each update returns a new Position object. The watchPosition method returns a unique transaction ID (number) associated with the asynchronous call. Use this ID to cancel the watchPosition call and to stop receiving location updates.
 
Syntax
 
watchPosition(showLocation, ErrorHandler, options);
 
Code
  1. <!DOCTYPE HTML>  
  2. <head>  
  3.    <script type="text/JavaScript">  
  4.       var watchID;        
  5.       var geoLoc;                    
  6.       function showLocation(position) {        
  7.           var latitude = position.coords.latitude;       
  8.           var longitude = position.coords.longitude;        
  9.           alert("Latitude : " + latitude + " Longitude: " + longitude);        
  10.       }                   
  11.       function errorHandler(err) {        
  12.           if (err.code == 1) {        
  13.               alert("Error: Access is denied!");        
  14.           }   
  15.       else if (err.code == 2) {        
  16.               alert("Error: Position is unavailable!");        
  17.           }        
  18.       }        
  19.       function getLocationUpdate() {                    
  20.           if (navigator.geolocation) {        
  21.               var options = { timeout: 60000 };        
  22.               geoLoc = navigator.geolocation;       
  23.               watchID = geoLoc.watchPosition(showLocation, errorHandler, options);        
  24.           }   
  25.       else {        
  26.               alert("Geolocation is not supported by browser!");        
  27.           }        
  28.       }       
  29.    </script>  
  30. </head>  
  31. <html>  
  32.    <body>  
  33.       <form>  
  34.          <input type="button" onclick="getLocationUpdate();"value="Watch Update"/>  
  35.       </form>  
  36.    </body>  
  37. </html> 
 
clearWatch( ): The clearWatch method cancels an ongoing watchPosition call. When cancelled, the watchPosition call stops retrieving updates about the current geographic location of the device. The clearWatch method does not return a value.
 
Syntax: clearWatch(watchId);
 
Parameters used:
 
watchID:: This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call.
 
Code
  1. <!DOCTYPE HTML><head><script type="text/javascript">var watchID;  
  2. var geoLoc;  
  3. function showLocation(position) {  
  4.     var latitude=position.coords.latitude;  
  5.     var longitude=position.coords.longitude;  
  6.     alert("Latitude : " + latitude + " Longitude: " + longitude);  
  7. }  
  8.   
  9. function errorHandler(err) {  
  10.     if (err.code==1) {  
  11.         alert("Error: Access is denied!");  
  12.     }  
  13.     else if (err.code==2) {  
  14.         alert("Error: Position is unavailable!");  
  15.     }  
  16. }  
  17.   
  18. function getLocationUpdate() {  
  19.     if (navigator.geolocation) {  
  20.         // timeout at 60000 milliseconds (60 seconds)  
  21.         var options= {  
  22.             timeout: 60000  
  23.         }  
  24.         ;  
  25.         geoLoc=navigator.geolocation;  
  26.         watchID=geoLoc.watchPosition(showLocation, errorHandler, options);  
  27.     }  
  28.     else {  
  29.         alert("Geolocation is not supported by your browser!");  
  30.     }  
  31. }  
  32.   
  33. function stopWatch() {  
  34.     geoLoc.clearWatch(watchID);  
  35. }  
  36. </script></head>  
  37. <html>  
  38.    <body>  
  39.       <form><input type="button" onclick="getLocationUpdate();" value="Watch Update"/><input type="button" onclick="stopWatch();" value="Stop Watch"/></form>  
  40.    </body>  
  41. </html> 
 

Error Callback Function ( )

 
The optional callback function that takes a "PositionError" object as its input parameter. This function is invoked when any error has occurred. In the request timeout case, the user has declined to share the location information, and when the location information is unavailable.
 
Position Options
 
Options available when the user retrieves the information.
  • enableHighAccuracy: Boolean. If true, the user agent will try to provide the most accurate position. This can result in a slower response time and higher power consumption. If false then a less accurate position will be obtained. The default value is false.
  • Timeout: Positive long value. It denotes the maximum time (in milliseconds) that the user agent can take to respond with the location data. The default value is Infinity.
  • maximumAge: Positive long value. It denotes how long (in milliseconds) the user agent can keep using the cached location data before trying to obtain new location data. A zero value indicates that the user agent must not use the cached location data and the infinity value indicates that the cached location data must be used by the user agent.
Use Google Maps
 
To plot our location on Google Maps we use the Google Maps API. The following explains all points step-by-step.
  1. Convert the latitude and longitude coordinates of the position object obtained using the Geolocation API into a Google maps latLng object.
    var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  2. Create a Map object specifying the map display options and the HTML div container where the map should be displayed. In the example we define the following three map options:
    • Zoom: Specifies the zoom level
    • Center: Specifies that the map should be centered at the user location
    • mapTypeId: Can be Roadmap, Satellite or Hybrid
    1. var mapOptions = {  
    2. zoom : 12,  
    3. center : googlePos,  
    4. mapTypeId : google.maps.MapTypeId.ROADMAP  
    5. };  
    6. var mapObj = document.getElementById('mapTxt');  
    7. var googleMap = new google.maps.Map(mapObj, mapOptions); 
  3. Now we create a marker at the location as in the following:
    1. var markerOpt = {  
    2. map : googleMap,  
    3. position : googlePos,  
    4. title : 'Hi , I am here',  
    5. animation : google.maps.Animation.DROP  
    6. };  
    7. var googleMarker = new google.maps.Marker(markerOpt); 
    The Code marker options indicate the following three important points:
    • Map: Map object where the marker should appear
    • Position: latlng position at which the marker should be displayed
    • Title: Title that should appear when we hover on the marker
  4. Find the address of your location using the reverse geocoding API and show the address obtained when you click on the marker.
    1. var geocoder = new google.maps.Geocoder();  
    2. geocoder.geocode({  
    3.     'latLng': googlePos  
    4. }, function (results, status) {  
    5.     if (status == google.maps.GeocoderStatus.OK) {  
    6.         if (results[1]) {  
    7.             var popOpts = {  
    8.                 content: results[1].formatted_address,  
    9.                 position: googlePos  
    10.             };  
    11.             var popup = new google.maps.InfoWindow(popOpts);  
    12.             google.maps.event.addListener(googleMarker, 'click'function () {  
    13.                 popup.open(googleMap);  
    14.             });  
    15.         } else {  
    16.             alert('No results found');  
    17.         }  
    18.     } else {  
    19.         alert('Geocoder failed due to: ' + status);  
    20.     }  
    21. }); 
    Now for the entire sample code:
    1. <!DOCTYPE html>  
    2. <html>  
    3. <head>  
    4. <title>Sample Map</title>  
    5. <style>  
    6. #mapdiv {  
    7.     margin: 0;  
    8.     padding: 0;  
    9.     width: 500px;  
    10.     height: 500px;  
    11. }  
    12. </style>  
    13.    
    14. <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>  
    15. <script>  
    16.     var watchId = null;  
    17.     function geoloc() {  
    18.         if (navigator.geolocation) {  
    19.             var optn = {  
    20.                 enableHighAccuracy: true,  
    21.                 timeout: Infinity,  
    22.                 maximumAge: 0  
    23.             };  
    24.             watchId = navigator.geolocation.watchPosition(showPosition, showError, optn);  
    25.         } else {  
    26.             alert('Geolocation is not supported in your browser');  
    27.         }  
    28.     }  
    29.    
    30.     function showPosition(position) {  
    31.         var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);  
    32.         var mapOptions = {  
    33.             zoom: 12,  
    34.             center: googlePos,  
    35.             mapTypeId: google.maps.MapTypeId.ROADMAP  
    36.         };  
    37.         var mapObj = document.getElementById('mapdiv');  
    38.         var googleMap = new google.maps.Map(mapObj, mapOptions);  
    39.         var markerOpt = {  
    40.             map: googleMap,  
    41.             position: googlePos,  
    42.             title: 'Hi , I am here',  
    43.             animation: google.maps.Animation.DROP  
    44.         };  
    45.         var googleMarker = new google.maps.Marker(markerOpt);  
    46.         var geocoder = new google.maps.Geocoder();  
    47.         geocoder.geocode({  
    48.             'latLng': googlePos  
    49.         }, function (results, status) {  
    50.             if (status == google.maps.GeocoderStatus.OK) {  
    51.                 if (results[1]) {  
    52.                     var popOpts = {  
    53.                         content: results[1].formatted_address,  
    54.                         position: googlePos  
    55.                     };  
    56.                     var popup = new google.maps.InfoWindow(popOpts);  
    57.                     google.maps.event.addListener(googleMarker, 'click'function () {  
    58.                         popup.open(googleMap);  
    59.                     });  
    60.                 } else {  
    61.                     alert('No results found');  
    62.                 }  
    63.             } else {  
    64.                 alert('Geocoder failed due to: ' + status);  
    65.             }  
    66.         });  
    67.     }  
    68.    
    69.     function stopWatch() {  
    70.         if (watchId) {  
    71.             navigator.geolocation.clearWatch(watchId);  
    72.             watchId = null;  
    73.    
    74.         }  
    75.     }  
    76.    
    77.     function showError(error) {  
    78.         var err = document.getElementById('mapdiv');  
    79.         switch (error.code) {  
    80.             case error.PERMISSION_DENIED:  
    81.                 err.innerHTML = "User denied the request for Geolocation."  
    82.                 break;  
    83.             case error.POSITION_UNAVAILABLE:  
    84.                 err.innerHTML = "Location information is unavailable."  
    85.                 break;  
    86.             case error.TIMEOUT:  
    87.                 err.innerHTML = "The request to get user location timed out."  
    88.                 break;  
    89.             case error.UNKNOWN_ERROR:  
    90.                 err.innerHTML = "An unknown error occurred."  
    91.                 break;  
    92.         }  
    93.     }  
    94.         </script>  
    95.    
    96.     </head>  
    97.     <body onload="geoloc()">  
    98.         <p id = 'mapdiv'></p>  
    99.         <button onclick="stopWatch()">  
    100.             Stop  
    101.         </button>  
    102.     </body>  
    103. </html> 
    Result
     


Similar Articles