The Geolocation API of web browsers allows websites to request access to the user’s geographical location. The API returns the user’s latitude and longitude coordinates (among other data).
Here is an example code snippet of how to use the Geolocation API:
if ("geolocation" in navigator) {
// check if geolocation is supported by the browser
navigator.geolocation.getCurrentPosition(position => {
// if access is granted, do something with the data
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
alert(`Your location is (${latitude}, ${longitude})`);
});
} else {
alert("Geolocation is not supported by this browser.");
}
In this code, we first check whether the browser supports the Geolocation API using the geolocation
property of the navigator
object.
If it is supported, we call the getCurrentPosition()
function to get the user’s location data. This function takes a callback function as an argument, which is called asynchronously when the data is available. The callback function receives a position
object that contains the user’s coordinates, among other properties.
If access to the location is granted, we extract the latitude
and longitude
coordinates from the position
object and do something with them. In this example, we show them in an alert box to the user.
If geolocation is not supported, we display an error message to the user.
The output of the above code would be an alert box that displays the user’s location in latitude and longitude coordinates. For example, if the user is located at latitude 37.7749 and longitude -122.4194, the alert would display the following message:
Your location is (37.7749, -122.4194)
Reference: