Geolocation API

The Geolocation API can ask the browser for an approximate device position, but the user and browser must allow the request.

What you will learn

Minimal request

if ('geolocation' in navigator) {
  navigator.geolocation.getCurrentPosition(
    ({ coords }) => console.log(coords.latitude, coords.longitude),
    (error) => console.warn('Location unavailable', error.message)
  );
}

Explain why the location is needed before asking. The success callback receives coordinates; the error callback handles a denied request, unavailable position, or timeout.

Privacy and safety

Common mistakes