Geolocation

HTML5 Geolocation or Geolocation API is used to get user Physical Location or geographical position using Device Sensors. Geolocation will return coordinates like, latitude, longitude and their accuracy. If device supports Barometer sensor, then we can also get altitude, altitude accuracy. For moving devices, we can also get direction and speed.

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 user privacy. HTML5 Geolocation API will always grant permission from the 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, or for one day in safari. 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>      

Geolocation Methods

There are three methods of navigator.geolocation object to get, watch and clear geolocation api.

  1. Get Geolocation
  2. Watch Geolocation
  3. Clear Watch

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.

Geolocation Properties
Property Value
latitude in °deg
longitude in °deg
altitude in meter
accuracy in meter
altitudeAccuracy in meter

Geolocation Example

Get Geo Location

Geolocation Example
Property Value
latitude
longitude
accuracy
altitude
altitudeAccuracy

<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 devices, 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 (in deg, 0 for north)
Speed ( in m/s)

    navigator.geolocation.watchPosition(success);

    function success(positions){
        
        var lat=positions.coords.latitude;
        var lon=positions.coords.longitude;
        var acc=positions.coords.accuracy;
        var alt=positions.coords.altitude;
        var altAcc=positions.coords.altitudeAccuracy;
        var head=positions.coords.heading;
        var speed=positions.coords.speed;                                
                                         
        console.log("Latitute is " + lat+ ", longitude is  "+ lon + " and accuracy is " + acc );
    }    

Clear Watch

clearWatch method of navigator.geolocation is used to clear watching geolocation by browser. To do this, we have to pass an argument in clearWatch method.


   // start watch
    var geo=navigator.geolocation.watchPosition(success);

    function success(positions){
        
        var lat=positions.coords.latitude;
        var lon=positions.coords.longitude;
        var acc=positions.coords.accuracy;
    }
    
    // clear watch
    
    navigator.geolocation.clearWatch(geo);
    

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>		
  1. HTML5 Geolocation is not supported in IE 8 and below.
  2. Geolocation is not permitted on http protocol now. Make sure your site is using SSL certificate, i.e, https
  3. For accuracy, turn on device location sensors or GPS.