Web Geolocation API
The Web Geolocation API is a modern web API that allows web applications to access the user's geographical location information, if the user grants permission.
The Geolocation API is accessed using the navigator.geolocation
object.
Here's an example of using the Geolocation API to get the user's current position:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
console.error("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
console.log("Latitude: " + position.coords.latitude +
"\nLongitude: " + position.coords.longitude);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
console.error("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
console.error("Location information is unavailable.");
break;
case error.TIMEOUT:
console.error("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
console.error("An unknown error occurred.");
break;
}
}
getLocation();
In this example:
- The
getLocation()
function checks if the Geolocation API is supported by the browser, and if it is, it calls thegetCurrentPosition()
method of thenavigator.geolocation
object. - This method takes two arguments: a success callback function and an error callback function.
- If the user grants permission to access their location, the success callback function
showPosition()
is called with aPosition
object representing the user's current position. - The Position object contains properties like
coords.latitude
andcoords.longitude
that can be used to get the user's latitude and longitude.
Real Life Example
Editor
Loading...