Get updates when a user's location changes
suggest changewatchPosition() reports location updates until the watch is cleared. Geolocation requires a secure context, user permission, and a clear privacy justification.
function updateLocation(position) {
const { latitude, longitude } = position.coords;
console.log(`New position at: ${latitude}, ${longitude}`);
}
function handleGeolocationError(error) {
console.error(`Unable to retrieve location: ${error.message}`);
}
let watchId;
if ('geolocation' in navigator) {
// Start only after the user explicitly enables continuous tracking.
watchId = navigator.geolocation.watchPosition(
updateLocation,
handleGeolocationError,
{ enableHighAccuracy: false, maximumAge: 30_000 },
);
} else {
console.log('Geolocation is not supported by this browser.');
}
Stop updates as soon as they are no longer needed:
if (watchId !== undefined) {
navigator.geolocation.clearWatch(watchId);
}
High-accuracy tracking may consume more power and take longer. Choose options based on the feature's actual precision and freshness requirements, and avoid retaining location data longer than necessary.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents