HTML5 Geolocation

The HTML Geolocation API is used to locate a user's position. There are many technique used to specify the location of a user. In web browser, WIFI or IP address are used to identify the location and in mobile based browsers WIFI, GPS or triangulation techniques are used to identify the location. Gelocation API use any of these techniques. Geolocation API protect 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 in a Google map.

Browser Support:

The following table show the first browser version that supports the Geolocation.

Browser

Firstly, we create a Web page and paste the following code in that page.

Html Code

  1. <body>  
  2.     <divid="div1"> <span>************HTML5 Geolocation*************</span> </div>  
  3.         <div>  
  4.             <inputtype="button" id="btn" value="Show My Location" onclick="loadScript()" /> </div>  
  5.         <divid="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 section 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 navigator object is used to check the compatibility of browsers for geolocation API.

Get User’s Location

navigator.geolocation.getCurrentPosition(Success, Show_Error, Geo_Options)

Location image

The getCurrentPosition method of navigator.geolocation object get the current location of user. This method takes three parameters (success callback method, error callback method and position option). Description of each parameter is described below.

Success Callback Method

In above code “Success” is called when we user accept the request for share location. Callback method contain a position object. This position object contain information about the user’s location. This position parameter contain the following information:
  1. Timestamp: Denote the time at which location is captured.
  2. Coords object: Contain information about location. The cords object contain the following information about the location of object.
Property Description
latitude, longitude Geographic coordinates in decimal degrees
Accuracy 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. };  
Error callback method is called when a position error is occurred. This error may be occurred due to any reason (request denied by user, request timeout, position not available or due to any other reason).

Position Option

Position option parameter provide some option during 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 value is true then browser provide more most accurate position. But it slow the process. Default value is false
Timeout Maximum Time in milliseconds that a user agent can take to retrieve location of user.
maximumAge It denotes that how long time ( milliseconds) the user agent can take using the cached location data before trying to obtain new location data. Zero means user agent doesn’t use cached location and infinity means user agent used cached location for a long time.

Show location of user in Google Map:

  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 above code we create a Google Map object and define the center of google map 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 web browser we get the current location of 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>  
Thanks for reading the article.

Up Next
    Ebook Download
    View all
    Learn
    View all