HTML Geolocation API Tutorial
The Geolocation API in HTML allows you to access a user's geographical location information through their device.
This information can be used for a wide range of applications, such as mapping, location-based services, and more.
Checking for Geolocation Support
- Before using the Geolocation API, you should check if the user's browser supports it.
if ("geolocation" in navigator) {
alert("Geolocation is supported.")
} else {
// Geolocation is not supported.
alert("Geolocation is not supported in this browser.");
}
Getting the User's Location
- You can use the navigator.geolocation.getCurrentPosition() method to get the user's current position.
navigator.geolocation.getCurrentPosition(function(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
alert("Latitude: " + latitude + ", Longitude: " + longitude);
}, function(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;
default:
alert("An unknown error occurred.");
break;
}
});
Watching for Changes in Location
- To continuously track the user's location, you can use the navigator.geolocation.watchPosition() method.
const watchId = navigator.geolocation.watchPosition(function(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log("Latitude: " + latitude + ", Longitude: " + longitude);
});
// To stop watching:
// navigator.geolocation.clearWatch(watchId);
Customizing Accuracy and Options
- You can specify options to control the desired accuracy and the maximum age of the retrieved location data.
const options = {
enableHighAccuracy: true, // Get the most accurate position.
maximumAge: 30000 // Maximum age of a cached position (in milliseconds).
};
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);