HTML5 Geolocation API allows websites to access the user’s location data with the user’s consent. The Geolocation API is implemented using JavaScript and is supported by modern browsers like Chrome, Firefox, and Safari.
Here’s how you can use the HTML5 Geolocation API:
- Check if the browser supports the Geolocation API:
if ("geolocation" in navigator) {
console.log("Geolocation is supported");
} else {
console.log("Geolocation is not supported");
}
- Get the user’s current location:
navigator.geolocation.getCurrentPosition(function(position) {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
});
The getCurrentPosition
method takes two arguments: a success callback and an error callback. The success callback is called with a Position
object as an argument, which contains the latitude and longitude of the user’s location.
- Watch the user’s location:
var watchId = navigator.geolocation.watchPosition(function(position) {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
});
The watchPosition
The method works similarly to getCurrentPosition but calls success calls whenever the user’s location changes. You can stop watching the user’s location by calling. navigator.geolocation.clearWatch(watchId)
.
Note: Always remember to obtain the user’s consent before accessing their location data.