Geolocation API
The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.
1. Checking for Support
Before using the API, check if the browser supports it.
if ("geolocation" in navigator) {
console.log("Geolocation is available");
} else {
console.log("Geolocation is not available");
}
2. Getting the Current Position
To get the user's current location, use the getCurrentPosition() method. It takes a success callback, an optional error callback, and an optional options object.
navigator.geolocation.getCurrentPosition(
(position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
},
(error) => {
console.error(`Error Code: ${error.code}, Message: ${error.message}`);
}
);
3. Watching the Position
If you need to track the user's location as they move (like a GPS navigation app), use watchPosition(). It fires the callback every time the location changes.
const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log(`New Position: ${position.coords.latitude}, ${position.coords.longitude}`);
},
(error) => {
console.error(error);
}
);
// To stop watching:
// navigator.geolocation.clearWatch(watchId);
4. Handling Errors
The error callback receives a GeolocationPositionError object.
1(PERMISSION_DENIED): The user denied the request for Geolocation.2(POSITION_UNAVAILABLE): Location information is unavailable.3(TIMEOUT): The request to get user location timed out.
5. Options
You can fine-tune the request using the options object.
const options = {
enableHighAccuracy: true, // Use GPS if available (consumes more battery)
timeout: 5000, // Time in ms to wait for a position
maximumAge: 0 // Maximum age in ms of a cached position
};
navigator.geolocation.getCurrentPosition(success, error, options);