A guide to Geolocation API

A guide to Geolocation API

·

5 min read

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.longitude}`);
          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:

Property Returns
coords.latitude The latitude as a decimal number
coords.longitude The longitude as a decimal number
coords.accuracy The accuracy of position
coords.altitude The altitude in meters above the mean sea level
coords.altitudeAccuracy The altitude accuracy of position
coords.heading The heading as degrees clockwise from north
coords.speed The speed in metres per second
timestamp The 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.


Help Needed

Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.

1.png


😀Thanks For Reading | ⚡ Happy Coding

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!