HTML Geolocation API
HTML Geolocation API
The Geolocation API lets a web page request the user's physical location — latitude, longitude, and accuracy — directly from the browser, using GPS on mobile devices or IP/Wi-Fi triangulation on desktops. It's the technology behind "find stores near me," delivery-tracking apps, weather widgets, and ride-sharing platforms.
How It Works
The API is exposed through navigator.geolocation, available in every modern browser. Because location data is sensitive, browsers always show a permission prompt asking the user to allow or deny access, and the API only works on secure (HTTPS) origins.
Getting the Current Position
navigator.geolocation.getCurrentPosition() takes a success callback, an optional error callback, and an optional options object. The success callback receives a position object containing coords.latitude, coords.longitude, and coords.accuracy (in meters).
Watching Position Over Time
For apps that need continuous updates (like live navigation), watchPosition() keeps calling the success callback whenever the device's location changes, and returns a watch ID that can later be passed to clearWatch() to stop tracking.
Handling Errors and Permissions
Users can deny the permission prompt, location services can be turned off, or the device may simply fail to get a fix. The error callback receives an error object with a code (1 = permission denied, 2 = position unavailable, 3 = timeout) and a message, so always handle this gracefully instead of assuming success.
Useful Options
- enableHighAccuracy — requests GPS-level precision (uses more battery).
- timeout — how long to wait (in ms) before giving up.
- maximumAge — allows reusing a cached position up to a given age in ms.
Common Use Cases
Store locators, weather apps, delivery ETA tracking, geo-tagged photos, ride-sharing pickup detection, and location-based content personalization all build on this API.
Press Run to execute.
Press Run to execute.
Write code that calls getCurrentPosition(). On success, log the coordinates. On failure, log a friendly message telling the user to enable location permissions, instead of a raw error object.
Press Run to execute.
Show expected output
Coordinates logged on success; a friendly 'please enable location access' message logged on error.This is a self-check — compare your result with the expected output above.
Was this page helpful?