Geolocation

JavaScript Geolocation or HTML5 Geolocation API is used client side API to get user Physical Location using geographical position or GPS Location by Device location Sensors. Geolocation will return coordinates like, latitude, longitude and accuracy. If device supports Barometer Sensor, then we can also get altitude and 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. However for development purpose, chrome allows geolocation in file protocol and localhost, i.e (127.0.0.1). IE 8 and below doesn't support HTML5 Geolocation API.

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. You need to give permission to allow web browser to trace geolocation from operating syatem.

  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 for success or error.

First parameter is callback function which will invoke if geolocation is allowed.

Second parameter is another callback function which will invoke if geolocation is not allowed or an error occurs.

getCurrentPosition with success callback


navigator.geolocation.getCurrentPosition(successCallback);        

getCurrentPosition with both success and error callback


navigator.geolocation.getCurrentPosition(successCallback,errorCallback);        

Success Callback

Success Callback returns GeolocationPosition. The GeolocationPosition Object includes coordinates of geolocation. There is also another property called timestamp which returns time when location is available.

GeolocationPosition {coords: GeolocationCoordinates, timestamp: 1697952365680}


navigator.geolocation.getCurrentPosition(x=>{
    console.log(x);
});        

Coords

Coords object includes coordinates. Coordinates are defined in Latitude and Longitude. There is also accuracy property of coordinates.

GeolocationCoordinates {latitude: 28.7825303, longitude: 77.3528988, altitude: null, accuracy: 13.243, altitudeAccuracy: null, …}


    navigator.geolocation.getCurrentPosition(x=>{
        console.log(x.coords);
    });        
    

Coordinates 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.

Latitude

Latitude is degree North or South from Equator. For Northern Hemisphere, latitude is always positive and for Southern Hemisphere its negative from 0 to 90 degree.

Longitude

Longitude is degree East or West from Equator. For Western Hemisphere, longitude is always positive and for Eastern Hemisphere its negative from 0 to 180 degree.

Accuracy

Accuracy is accuracy in meters for Longitude and latitude.

Altitude

Altitude is altitude in meters from sea level or null.

Altitude Accuracy

Altitude Accuracy is accuracy in meters for altitude or null.

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(pos){
        
    const lat=pos.coords.latitude;
    const lon=pos.coords.longitude;
    const acc=pos.coords.accuracy;
                                         
console.log(`Latitude is ${lat}, longitude is ${lon} and accuracy is ${acc}`);
    
}


function error(err){
    console.warn("Error " + err.message);
}

</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("Latitude 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);
    

Weather Api

In this example, we will learn how to check local Weather using geolocation api. I am using https://openweathermap.org/ free api for Weather updates.

To get Free API Key, login to https://openweathermap.org/ and register for free.

 


document.querySelector('button').addEventListener("click",function(){

    navigator.geolocation.getCurrentPosition(done,error);
            
    function done(x){
    let lat=x.coords.latitude;
    let lon=x.coords.longitude;
    let apiKey="abcdefgh1234";
    
    fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&APPID=${apiKey}&units=metric`).then(i=>i.json()).then(i=>console.log(i));

    }
    function error(x){
    console.log(x.message);
    }
});

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.