Skip to content
HTML5

Geolocation

Get the user's position and watch for changes.

#geolocation#location

Code

html5
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);