Geolocation API
In one line
The Geolocation API lets the browser request the user's geographic position (latitude, longitude) with their permission.
In simple words
The Geolocation API lets you ask the browser for the user's current position. It returns a Position object with coordinates — latitude, longitude, accuracy, and optionally altitude, speed, and heading. The browser prompts the user for permission, so this only works over HTTPS and with consent.
You call navigator.geolocation.getCurrentPosition(success, error, options) for a one-time read, or watchPosition to receive continuous updates as the user moves (useful for navigation apps). The options let you request high accuracy, set a timeout, and control caching of older readings.
Use cases: showing nearby results on a map, defaulting a weather app to the user's city, tagging a post with location, and turn-by-turn navigation. Always handle the error callback (permission denied, position unavailable, timeout) and provide a graceful fallback — never block the UI on geolocation.
Example
navigator.geolocation.getCurrentPosition(
(pos) => {
const { latitude, longitude } = pos.coords;
console.log(`You are at ${latitude.toFixed(4)}, ${longitude.toFixed(4)}`);
},
(err) => console.warn("Location denied:", err.message),
{ enableHighAccuracy: true, timeout: 10000 }
);On success, pos.coords gives latitude/longitude. The error callback handles denial or timeout. enableHighAccuracy requests GPS precision.
Related terms
Related Resources
Related Lessons
- Geolocation
Learn location APIs.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.