HTML5 Geolocation

Introduction 

 
The HTML Geolocation API is used to locate a user's position. There are many techniques used to specify the location of a user. In a web browser, WIFI or IP address is used to identify the location and in mobile-based browsers WIFI, GPS or triangulation techniques are used to identify the location. Geolocation API uses any of these techniques. Geolocation API protects the user’s privacy by accepting the permission of a user before sending location information to any website.
In this article, we learn how to identify the user location and show it on a Google map.
 

Browser Support 

 
The following table shows the first browser version that supports Geolocation.
 
Browser
 
Firstly, we create a Web page and paste the following code in that page. 
 
Html Code
  1. <body>    
  2.     <dividdivid="div1"> <span>************HTML5 Geolocation*************</span> </div>    
  3.         <div>    
  4.             <inputtypeinputtype="button" id="btn" value="Show My Location" onclick="loadScript()" /> </div>    
  5.         <dividdivid="map">    
  6.             </div>    
  7. </body>    
Script
  1. <script>    
  2.     $(document).ready(function()    
  3.     {    
  4.         $("#btn").click(function()    
  5.         {    
  6.             if (navigator.geolocation)    
  7.             {    
  8.                 varGeo_Options = {    
  9.                     enableHighAccuracy: false,    
  10.                     timeout: Infinity,    
  11.                     maximumAge: 0    
  12.                 }    
  13.                 navigator.geolocation.getCurrentPosition(Success, Show_Error, Geo_Options)    
  14.             }    
  15.             else    
  16.             {    
  17.                 alert("OOPS! Your Browser Doesn't Support GeoLocation \n" + "Please Update Your Browser")    
  18.             }    
  19.     
  20.             function Success(position)    
  21.             {    
  22.                 alert(" Show My Location \n" + "Latitude is " + position.coords.latitude + "\n Longitude is " + position.coords.longitude + "\n Accuracy is " + position.coords.accuracy + "\n Altitude is " + position.coords.altitude + "\n Altitude Accuracy is " + position.coords.altitudeAccuracy);    
  23.                 varmapProp = {    
  24.                     center: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),    
  25.                     zoom: 13,    
  26.                     mapTypeId: google.maps.MapTypeId.ROADMAP    
  27.                 }    
  28.                 var marker = newgoogle.maps.Marker(    
  29.                 {    
  30.                     position: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),    
  31.                     title: 'Hello ! I am Here!'    
  32.                 });    
  33.                 var map = newgoogle.maps.Map(document.getElementById("map"), mapProp);    
  34.                 marker.setMap(map);    
  35.             }    
  36.             functionShow_Error(error)    
  37.             {    
  38.                 switch (error.code)    
  39.                 {    
  40.                     caseerror.PERMISSION_DENIED: alert("User denied the request");    
  41.                     break;    
  42.                     caseerror.POSITION_UNAVAILABLE: alert("Location information Not available.");    
  43.                     break;    
  44.                     caseerror.TIMEOUT: alert("Request time out");    
  45.                     break;    
  46.                     caseerror.UNKNOWN_ERROR: alert("Unknown error ");    
  47.                     break;    
  48.                 }    
  49.             };    
  50.         })    
  51.     });    
  52. </script>  
Now we divide the script in several sections and read about each section separately.
 
Check Browser Compatibility
  1. if (navigator.geolocation)    
  2. {    
  3.     // Geolocation Code    
  4. }    
  5. else    
  6. {    
  7.     alert("OOPS! Your Browser Doesn't Support GeoLocation \n" + "Please Update Your Browser")    
  8. }    
The geolocation property of the navigator object is used to check the compatibility of browsers for geolocation API.
 

Get a User’s Location

  1. navigator.geolocation.getCurrentPosition(Success, Show_Error, Geo_Options)   
 
Location image
 
The getCurrentPosition method of navigator.geolocation object gets the current location of the user. This method takes three parameters (success callback method, error callback method and position option). The description of each parameter is described below. 
 

Success Callback Method

In the above code “Success” is called when we user accepts the request for share location. The callback method contain a position object. This position object contains information about the user’s location. This position parameter contains the following information:
  1. Timestamp: Denote the time at which location is captured.
  2. Coords object: Contain information about the location. The cords object contains the following information about the location of the object.
Property Description
latitude, longitude Geographic coordinates in decimal degrees
Accuracy The accuracy level of coordinates
Speed Indicates relative speed in meters per second
Heading Provides 360-degree heading information
Altitude Height of the position above the sea level in meters
AltitudeAccuracy Accuracy of actual attitude value obtained in meters. Big the number lesser is the accuracy
 
When success method call it will show the information about user location,
  1. function Success(position) {    
  2.     
  3.    alert(" Show My Location \n" +    
  4.    "Latitude is " + position.coords.latitude +    
  5.    "\n Longitude is " + position.coords.longitude +    
  6.    "\n Accuracy is " + position.coords.accuracy +    
  7.    "\n Altitude is " + position.coords.altitude +    
  8.    "\n Altitude Accuracy is " + position.coords.altitudeAccuracy);    
  9. }    
Output
 
Message
  

Error Callback Method

  1. functionShow_Error(error)    
  2. {    
  3.     switch (error.code)    
  4.     {    
  5.         caseerror.PERMISSION_DENIED: alert("User denied the request");    
  6.         break;    
  7.         caseerror.POSITION_UNAVAILABLE: alert("Location information Not available.");    
  8.         break;    
  9.         caseerror.TIMEOUT: alert("Request time out");    
  10.         break;    
  11.         caseerror.UNKNOWN_ERROR: alert("Unknown error ");    
  12.         break;    
  13.     }    
  14. };    
The error callback method is called when a position error occurs. This error may be occurred due to any reason (request denied by the user, request timeout, a position not available or due to any other reason).
 

Position Option 

 
The position option parameter provides some options during the retrieval of location information. This parameter contains the following options.
  1. varGeo_Options = {    
  2.     enableHighAccuracy: false,    
  3.     timeout: Infinity,    
  4.     maximumAge: 0    
  5. }    
Option Description
enableHighAccuracy If the value is true then the browser provides a more most accurate position. But it slows the process. The default value is false
Timeout Maximum Time in milliseconds that a user agent can take to retrieve the location of the user.
maximumAge It denotes how long time ( milliseconds) the user agent can take using the cached location data before trying to obtain new location data. Zero means the user agent doesn’t use cached location and infinity means the user agent used cached location for a long time.
 
Show the location of the user on Google Maps.
  1. varmapProp = {    
  2.     center: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),    
  3.     zoom: 13,    
  4.     mapTypeId: google.maps.MapTypeId.ROADMAP    
  5. }    
  6. var marker = newgoogle.maps.Marker(    
  7. {    
  8.     position: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),    
  9.     title: 'Hello ! I am Here!'    
  10. });    
  11. var map = newgoogle.maps.Map(document.getElementById("map"), mapProp);    
  12. marker.setMap(map);     
Using the above code we create a Google Map object and define the center of google Maps using latitude and longitude retrieved from geolocation API. We also create a marker and maintain the property of marker and at last, we assign this marker to map object.
 
So when we run this program in a web browser we get the current location of the current location in Google Map.
 
Location
 
Complete code
  1. <htmlxmlns="http://www.w3.org/1999/xhtml">    
  2.     <headrunat="server">    
  3.         <title></title>    
  4.         <scriptsrc="jquery-ui-1.11.4.custom/jquery-ui-1.11.4.custom/external/jquery/jquery.js">    
  5.             </script>    
  6.             <!--Goolge API-->    
  7.             <scriptsrc="http://maps.googleapis.com/maps/api/js">    
  8.                 </script>    
  9.                 </head>    
  10.                 <script>    
  11.                     $(document).ready(function()    
  12.                     {    
  13.                         $("#btn").click(function()    
  14.                         {    
  15.                             if (navigator.geolocation)    
  16.                             {    
  17.                                 varGeo_Options = {    
  18.                                     enableHighAccuracy: false,    
  19.                                     timeout: Infinity,    
  20.                                     maximumAge: 0    
  21.                                 }    
  22.                                 navigator.geolocation.getCurrentPosition(Success, Show_Error, Geo_Options)    
  23.                             }    
  24.                             else    
  25.                             {    
  26.                                 alert("OOPS! Your Browser Doesn't Support GeoLocation \n" + "Please Update Your Browser")    
  27.                             }    
  28.     
  29.                             function Success(position)    
  30.                             {    
  31.                                 alert(" Show My Location \n" + "Latitude is " + position.coords.latitude + "\n Longitude is " + position.coords.longitude + "\n Accuracy is " + position.coords.accuracy + "\n Altitude is " + position.coords.altitude + "\n Altitude Accuracy is " + position.coords.altitudeAccuracy);    
  32.                                 varmapProp = {    
  33.                                     center: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),    
  34.                                     zoom: 13,    
  35.                                     mapTypeId: google.maps.MapTypeId.ROADMAP    
  36.                                 }    
  37.                                 var marker = newgoogle.maps.Marker(    
  38.                                 {    
  39.                                     position: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),    
  40.                                     title: 'Hello ! I am Here!'    
  41.                                 });    
  42.                                 var map = newgoogle.maps.Map(document.getElementById("map"), mapProp);    
  43.                                 marker.setMap(map);    
  44.                             }    
  45.                             functionShow_Error(error)    
  46.                             {    
  47.                                 switch (error.code)    
  48.                                 {    
  49.                                     caseerror.PERMISSION_DENIED: alert("User denied the request");    
  50.                                     break;    
  51.                                     caseerror.POSITION_UNAVAILABLE: alert("Location information Not available.");    
  52.                                     break;    
  53.                                     caseerror.TIMEOUT: alert("Request time out");    
  54.                                     break;    
  55.                                     caseerror.UNKNOWN_ERROR: alert("Unknown error ");    
  56.                                     break;    
  57.                                 }    
  58.                             };    
  59.                         })    
  60.                     });    
  61.                 </script>    
  62.                 <style>    
  63.                     #div1 {    
  64.                         background-color: coral;    
  65.                         color: ButtonHighlight;    
  66.                         font-size: 30px;    
  67.                         height: 80px;    
  68.                         width: 1000px;    
  69.                         text-align: center;    
  70.                         margin-left: 150px    
  71.                     }    
  72.                       
  73.                     #map {    
  74.                         height: 700px;    
  75.                         width: 1000px;    
  76.                         text-align: center;    
  77.                         margin-left: 150px;    
  78.                         margin-top: 10px    
  79.                     }    
  80.                       
  81.                     #btn {    
  82.                         color: chocolate;    
  83.                         background-color: aquamarine;    
  84.                         font-size: 26px;    
  85.                         margin-left: 550px;    
  86.                         margin-top: 10px    
  87.                     }    
  88.                 </style>    
  89.     
  90.                 <body>    
  91.                     <divid="div1"> <span>************HTML5 Geolocation*************</span> </div>    
  92.                         <div>    
  93.                             <inputtype="button" id="btn" value="Show My Location" onclick="loadScript()" />     
  94.                         </div>    
  95.                         <divid="map">    
  96.                      </div>    
  97.                 </body>    
  98.     
  99.              </html>    

Summary

 
In this article, we learned about HTML5 Geolocation. 
 
Thanks for reading the article.