March 21, 2024

JS Geolocation API – Get a User's Location

The JavaScript Geolocation API provides access to geographical location data associated with a user's device. This can be determined using GPS, WIFI, IP Geolocation and so on.

Geolocation is most accurate for devices with GPS, like smartphones.

To protect the user's privacy, it requests permission to locate the device. If the user grants permission, you will gain access to location data such as latitude, longitude, altitude and speed etc.

The Geolocation API is available through the navigator.geolocation object.

If the object exists, geolocation services are available. You can test for the presence of geolocation:

if ("geolocation" in navigator) {
  console.log("geolocation is available");
} else {
  console.log("geolocation is not available");
}

navigator.geolocation object provides the method getCurrentPosition() to return the user's position.

There are three possible arguments with this method:

  • A success callback (required)
  • An error callback (optional)
  • An options object (optional)

The example below calls getCurrentPosition() with both success and error callbacks, and returns the latitude and longitude of the user's position:

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(usePositionData, useError);
  } else {
    console.log("Geolocation is not supported by this browser.");
  }
}

function usePositionData(position) {
	//do something with position data.
	console.log("Latitude: " + position.coords.latitude);
	console.log("Longitude: " + position.coords.longitude);
}

function useError(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;
  }
}

Related Post(s):

No comments:

Post a Comment