Geolocation

HTML5 Geolocation or Geolocation API is used to get user Physical Location or geographical position using Device Sensors. Earlier IP based location was used, but now Geo Location is more popular as it is more accurate. As Geolocation is related to user privacy, first browser will grant your permission.


Geolocation Permission

Getting user physical location comes under privacy. HTML5 geolocation will always grant permission from user to check geolocation. If a user allows, geolocation will work, else geolocation will be blocked.

Once Geolocation is allowed, the browser will save this, and allow geolocation every time user visit same website. However a user can block geolocation of same website in browser settings.

Geolocation Permission Popup

HTML5 Geolocation
Html5 Geolocation permission

Check Geolocation

Geolocation is supported on https protocol & HTML5 Based browsers only. IE 8 and low doesn't support Geolocation. However for development purpose, chrome allows geolocation in file protocol.

For Production purpose, use https protocol.

Check Geo Location


<script>
    if(navigator.geolocation) {
        alert("geolocation supported")
    }
    else{
    alert("geolocation not supported")
    }  
</script>      

Get Geolocation

To get geolocation, use navigator.geolocation.getCurrentPosition() function. This function can have one or two parameters. These parameters are callback functions.

First parameter is name of function which will invoke if geolocation is allowed.

Second parameter is name of function which will invoke if geolocation is not allowed.


Geolocation Properties

The first callback function (success) will have a parameter (exp positions). positions is having a property coords. Now positions.coords will call geolocation properties. Here are some properties of geolocation coords.

  1. latitude , in degrees.
  2. longitude, in degrees.
  3. altitude, in meters, null if altitude is not available.
  4. accuracy, accuracy of latitude & longitude in meters.
  5. altitudeAccuracy , in meters.
  6. heading, in degrees. 0 for north, 90 for east. If speed is 0, its null.
  7. speed, in m/s.

Geolocation Code

Get Geo Location


<script>
    navigator.geolocation.getCurrentPosition(success,error);
	
    function success(positions){
        
        var lat=positions.coords.latitude;
        var lon=positions.coords.longitude;
        var acc=positions.coords.accuracy;
                                         
        alert("Latitute is " + lat+ ", longitude is  "+ lon + " and accuracy is " + acc );
    }
    
    
    function error(){
        alert("geolocation is denied");
    }
    
</script>
			

Watch Position

For a moving device, the properties will change. Even if accuracy changes after some time, we cannot get the new properties in getCurrentPosition method.

To resolve this, use navigator.geolocation.watchPosition() method. This method is used same like navigator.geolocation.getCurrentPosition() method. See example

Watch Geo Location

Property Value
Latitude
Longitude
Accuracy
Altitude
Altitude Accuracy
Heading
Speed

    navigator.geolocation.watchPosition(success);

    function success(positions){
        
        var lat=positions.coords.latitude;
        var lon=positions.coords.longitude;
        var acc=positions.coords.accuracy;
                                         
        alert("Latitute is " + lat+ ", longitude is  "+ lon + " and accuracy is " + acc );
    }    

Google Map Direction API

We all have used google direction in google maps. Let create the same Direction API using HTML5 Geolocation and google maps.


<button onclick="getLocation()"> Get Direction </button>		
<script>
	function getLocation()
  {
  if(navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition,showError); 
	
    }
  else{
     alert("Geolocation is not supported by this browser.";)
      }
  }
	
function showPosition(position)
  {
  var lat=position.coords.latitude;        // latitude position
  var lon=position.coords.longitude;       // longitude position
  var acc=position.coords.accuracy;        // longitude accuracy in meters
  
   window.open("https://www.google.com/maps/dir/" + lat + "," + lon + "/Tech+Altum, +Noida,+Uttar+Pradesh+201301,+India/@28.585731,77.1751928,12z/data=!3m1!4b1!4m8!4m7!1m0!1m5!1m1!1s0x390ce45eed7c8971:0xcbb6c33c43ba8f02!2m2!1d77.313203!2d28.582582"); 
  }
  
function showError(error)
  {
  switch(error.code) 
    {
    case error.PERMISSION_DENIED:
    alert("User denied the request for Geolocation.")
      break;
    case error.POSITION_UNAVAILABLE:
    alert("Location information is unavailable.")  
      break;
    case error.TIMEOUT:
      alert("The request to get user location timed out.")
      break;
    case error.UNKNOWN_ERROR:
      alert("An unknown error occurred.")
      break;
    }
  }
</script>		

HTML5 Geolocation is not supported in IE 8 and Below. To run geolocation code locally, please use localhost. Geolocation is not permitted on file protocol. Make sure your device location sensors or GPS is on.