Get updates when a user's location changes

suggest change

watchPosition() 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents