Geolocation API basics
The Geolocation API asks the browser for a position estimate; the browser and user decide whether the request may proceed.
What you will learn
- What a position object contains
- Why accuracy and permission are not guaranteed
- How to build a useful experience when location is unavailable
Requesting a position
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords;
console.log(latitude, longitude, accuracy);
},
(error) => console.warn(error.code, error.message)
);The coordinates are an estimate. The accuracy value is expressed in meters and does not mean that the result is exact.
Permission is part of the feature
Explain what the user gains before requesting location. A denial, timeout, or unavailable position is a normal outcome, not an exceptional one.
Common mistakes
- Do not request precise location before it is needed.
- Do not show a precise coordinate in a public interface without a clear reason.
- Do not treat the browser result as proof of identity or authorization.
- Provide manual location entry or another fallback.