Skip to content
HTML5

Geolocation

Get the user's position and watch for changes.

By EZ4Code Team
geolocationlocation

Code

if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(
    pos => {
      const { latitude, longitude, accuracy } = pos.coords;
      console.log("Lat:", latitude, "Lng:", longitude, "+/-", accuracy, "m");
    },
    err => {
      console.error(err.message);  // permission denied, etc.
    },
    { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
  );
} else {
  console.log("Geolocation not supported");
}

// Watch position changes (e.g., for navigation)
const watchId = navigator.geolocation.watchPosition(
  pos => console.log(pos.coords),
  err => console.error(err)
);

// Stop watching
navigator.geolocation.clearWatch(watchId);

Explanation

navigator.geolocation prompts the user for permission and returns coordinates via a callback. getCurrentPosition takes success and error callbacks plus options like enableHighAccuracy for GPS. watchPosition streams updates and returns an id used with clearWatch to stop tracking.

More HTML5 Snippets