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
- How to request a current position
- Why secure contexts and permission matter
- How to handle denial, unavailable data, and timeouts
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
- Ask only when the feature is needed, not immediately on page load without context.
- Use HTTPS and request the minimum accuracy and duration your feature needs.
- Do not expose precise location in a public URL, log, or analytics event.
- Provide a useful alternative when the user refuses permission.
Common mistakes
- Assuming a position is always available or accurate.
- Showing a map without explaining how location data is used.
- Failing silently when a browser or device has no location source.