The HTML Geolocation API is a browser API used to obtain the geographical location information of a user’s device. With this API, a web page can access a user’s location data through the user’s device.
To use the Geolocation API, you can call the getCurrentPosition()
method, which will prompt the user to grant the web page permission to access their location information. This method accepts three arguments: a success callback function that receives the location information, an error callback function that is called when an error occurs, and an options object that specifies the desired accuracy and other options.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API Example</title>
</head>
<body>
<h1>Geolocation Example</h1>
<p id="demo">Click the button to get your location.</p>
<button onclick="getLocation()">Get Location</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
document.getElementById("demo").innerHTML = "Latitude: " + latitude +
"<br>Longitude: " + longitude + "<br>Accuracy: " + accuracy + " meters.";
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
</script>
</body>
</html>
This code displays a button on the web page that, when clicked, prompts the user for permission to access their location. If the user grants permission, the getCurrentPosition()
method calls the showPosition()
function, which displays the latitude, longitude, and accuracy of the user’s location. If an error occurs, the showError()
function displays an appropriate error message.