Rahul
5 supporters
A guide to Geolocation API

A guide to Geolocation API

Nov 28, 2020

The Geolocation API is used to get the geographical position of a user. Since this can compromise privacy, the position is not available unless the user approves it.

The Geolocation API is supported by all major browser.

Using the Geolocation API

getCurrentPosition()

The getCurrentPosition() method is used to return the user's position. It takes two function as parameters - the first one returns the user's position and the second is used to handle errors in case the browser fails to get the user's location.

navigator.geolocation.getCurrentPosition(showPosition, showErrors)

The second parameter is option though.

Example 1

This is a very simple example of implementing the geolocation API without handling any errors. The getCurrentPosition() method returns object.

getLocation = ( ) => {
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
         console.log(`Longitude: ${position.coords.logitude}`);
          console.log(`Latitude: ${position.coords.latitude}`);
    });
}
else {
   console.log(`Geolocation is not supported by this browser.`);
   }
}
getLocation();

On the line 2 we are checking if the geolocation is supported by the browser or not. If yes, we have logged the longitude and latitude by using the coords.longitude and coords.latitude properties.

The examples below illustrates how to handle errors:

getLocation = () => {
  if (navigator.geolocation) { 
   navigator.geolocation.getCurrentPosition(showPosition, showError); 
} else {
   console.log("Geolocation is not supported by your browser");
  }
}

showPosition = (position) => {
  console.log(`Latitude: ${position.coords.latitude}
    Longitude: ${position.coords.longitude}`);
}

showError => (error) => {
  switch(error.code) {
   case error.PERMISSION_DENIED:
     console.log("User denied the request for Geolocation.");break;
    case error.POSITION_UNAVAILABLE:
      console.log("Location information is unavailable.");break;
     case error.TIMEOUT:
       console.log("The request to get user location timed out. ");break;
      case error.UNKNOWN_ERROR:
        console.log("An unknown error occurred.");break;
  }
}

getCurrentPosition() and other properties

The getCurrentPosition() method returns an object. We already saw two of its properties : coords.latitude and coords.longitude. The other properties of this object are:

PropertyReturnscoords.latitudeThe latitude as a decimal numbercoords.longitudeThe longitude as a decimal numbercoords.accuracyThe accuracy of positioncoords.altitudeThe altitude in meters above the mean sea levelcoords.altitudeAccuracyThe altitude accuracy of positioncoords.headingThe heading as degrees clockwise from northcoords.speedThe speed in metres per secondtimestampThe date/time of the response

watchPostion() and clearWatch()

The Geolocation object also has two more interesting methods:

watchPostion(): Returns the current position of the user and continues to return updated position as the user moves (like gps in vehicle).

clearWatch(): Stops the above(watchPostion()) method.

Example:

The example below shows the watchPostion() method. You can test this on a GPS enabled device like a smartphone.

getLocation = () => {
  if (navigator.geolocation) {
    naviagtor.geolocation.watchPosition(postion => {
     console.log(`Latitude: ${position.coords.latitude} <br>
       Longitude: ${position.coords.longitude}` );
   });
} else {
   console.log("Geolocation is not supported by this browser. "); 
  }
}

You can use a map API (like google maps) to present these informational real-time on a map.

😀Thanks For Reading | ⚡ Happy Coding



Enjoy this post?

Buy Rahul a coffee

More from Rahul