HTML APIs
HTML Geolocation
The Geolocation API lets a web page request the user's geographic location (latitude, longitude, accuracy and more) directly from the browser, always with the user's explicit permission.
What is the Geolocation API?
The Geolocation API is a browser API exposed through the global navigator.geolocation object. It gives web applications access to the device's location using signals such as GPS, Wi-Fi networks, cell towers and IP address. It is not part of the HTML markup itself; it is a JavaScript API standardised by the W3C that ships in every modern browser.
Typical uses include showing nearby stores on a map, auto-filling a delivery address, providing local weather, or tagging content with a location. Because location is sensitive personal data, the browser always asks the user for permission before revealing it.
Reading the location once: getCurrentPosition()
getCurrentPosition() takes a success callback, an optional error callback, and an optional options object. When it succeeds, the browser passes a GeolocationPosition object whose coords property holds the actual data.
<button id="locate">Show my location</button>
<p id="output">Location will appear here.</p>
<script>
const output = document.getElementById("output");
document.getElementById("locate").addEventListener("click", () => {
if (!("geolocation" in navigator)) {
output.textContent = "Geolocation is not supported by this browser.";
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords;
output.textContent =
`Latitude: ${latitude.toFixed(5)}, ` +
`Longitude: ${longitude.toFixed(5)} ` +
`(accurate to ~${Math.round(accuracy)} m)`;
},
(error) => {
output.textContent = "Error: " + error.message;
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
});
</script>The success callback receives a GeolocationPosition. Its coords object exposes latitude, longitude, accuracy (in metres), and optionally altitude, altitudeAccuracy, heading and speed. The timestamp property records when the reading was taken.
Tracking movement: watchPosition()
When you need continuous updates (for example, live navigation), watchPosition() registers a callback that fires every time the position changes. It returns a numeric watch ID that you pass to clearWatch() to stop tracking and save battery.
let watchId = navigator.geolocation.watchPosition(
(position) => {
console.log("Moved to:", position.coords.latitude, position.coords.longitude);
},
(error) => console.warn("Watch error:", error.message),
{ enableHighAccuracy: true, maximumAge: 5000 }
);
// Later, stop tracking:
// navigator.geolocation.clearWatch(watchId);The Geolocation API only works in a secure context. The page must be served over HTTPS (localhost is treated as secure for development). On plain http:// pages, navigator.geolocation calls are blocked in all modern browsers.
Permission: the first call triggers a browser prompt asking the user to Allow or Block location. If the user denies it, the error callback receives a GeolocationPositionError with code 1 (PERMISSION_DENIED). You can pre-check status with the Permissions API: navigator.permissions.query({ name: 'geolocation' }).
Key methods, objects and error codes
| Member | Type | Purpose |
|---|---|---|
| getCurrentPosition(success, error?, options?) | Method | Get the location a single time |
| watchPosition(success, error?, options?) | Method | Get repeated updates as the device moves; returns a watch ID |
| clearWatch(id) | Method | Stop a watch started by watchPosition() |
| position.coords | GeolocationCoordinates | latitude, longitude, accuracy, altitude, heading, speed |
| position.timestamp | Number (ms) | When the reading was taken |
| error.code | Number | 1 = PERMISSION_DENIED, 2 = POSITION_UNAVAILABLE, 3 = TIMEOUT |
The options object accepts enableHighAccuracy (request GPS-level precision), timeout (max milliseconds to wait), and maximumAge (accept a cached position up to this many milliseconds old).
