JavaScript Geolocation API
In the realm of modern web development, leveraging geolocation data offers a transformative edge. This guide delves into JavaScript's Geolocation API, providing
The Geolocation API lets a web page ask the browser where the user's device is. With a user's permission, you get back coordinates (latitude and longitude) that you can use to show nearby results, center a map, or tag content with a location. This guide covers the full API: checking support, reading the current position once, watching position changes over time, the options that control accuracy and timing, and how to handle errors and permissions correctly.
Introduction to the Geolocation API
The Geolocation API is part of the browser environment (the navigator object), not the JavaScript language itself. If you are new to the difference between language features and browser-provided APIs, see the Browser environment, specs chapter for context.
The API exposes three methods on navigator.geolocation:
getCurrentPosition()— get the position once.watchPosition()— get the position repeatedly as the device moves.clearWatch()— stop awatchPosition()subscription.
Two requirements you cannot skip
- Secure context. Browsers only expose geolocation on pages served over HTTPS (or
localhostduring development). On a plainhttp://page,navigator.geolocationmay be missing or every call fails. This is a privacy and security measure. - User permission. The browser shows a prompt the first time a page requests location. Nothing happens until the user clicks Allow. If they choose Block, your error callback fires with a
PERMISSION_DENIEDcode.
Checking for API availability
Always feature-detect before using the API, because old browsers and insecure pages may not provide it.
Getting the current position
To fetch the device's location a single time, call getCurrentPosition(success, error, options). Only the first argument is required.
const options = {
// Ask for the highest-accuracy position available (e.g. GPS on mobile).
enableHighAccuracy: true,
// Give up after 5 seconds if no position is returned.
timeout: 5000,
// Never use a cached position; always fetch a fresh one.
maximumAge: 0
};
function success(position) {
const { latitude, longitude, accuracy } = position.coords;
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
console.log(`Accurate to within ${accuracy} meters`);
}
function error(err) {
console.error(`Error (${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);The position object
The success callback receives a GeolocationPosition object with two fields:
position.timestamp— when the reading was taken (milliseconds since the epoch).position.coords— aGeolocationCoordinatesobject containing:
| Property | Description |
|---|---|
latitude | Degrees north/south (decimal). |
longitude | Degrees east/west (decimal). |
accuracy | Accuracy of latitude/longitude in meters. |
altitude | Height in meters above sea level (or null). |
altitudeAccuracy | Accuracy of altitude in meters (or null). |
heading | Direction of travel in degrees clockwise from north (or null). |
speed | Ground speed in meters per second (or null). |
The heading and speed fields are usually only populated on devices that are actually moving and have the right sensors.
The options object
All three options are optional. Choose them based on your use case:
| Option | Default | What it does |
|---|---|---|
enableHighAccuracy | false | When true, requests the most precise source (GPS). Slower and uses more battery. |
timeout | Infinity | Maximum milliseconds to wait before calling the error callback with TIMEOUT. |
maximumAge | 0 | How old (in ms) a cached position may be before a fresh one is required. Use a larger value to reuse a recent reading and respond faster. |
A common trade-off: set enableHighAccuracy: false and a non-zero maximumAge when an approximate, fast result is fine (such as "stores near me"); use enableHighAccuracy: true with maximumAge: 0 for turn-by-turn navigation.
Handling errors
When a request fails, the error callback receives a GeolocationPositionError. Its code property tells you exactly what went wrong:
function error(err) {
switch (err.code) {
case err.PERMISSION_DENIED: // 1
console.error("User denied the request for location.");
break;
case err.POSITION_UNAVAILABLE: // 2
console.error("Location information is unavailable.");
break;
case err.TIMEOUT: // 3
console.error("The request to get location timed out.");
break;
default:
console.error(`An unknown error occurred: ${err.message}`);
}
}PERMISSION_DENIED(1) — the user blocked location access, or the page is not a secure context.POSITION_UNAVAILABLE(2) — the device could not determine its location (no GPS/Wi-Fi signal, etc.).TIMEOUT(3) — no position was obtained within thetimeoutyou set.
Checking permission ahead of time
You can inspect the geolocation permission without triggering a prompt using the Permissions API. This is useful for tailoring your UI (for example, hiding a "Find me" button if access is already blocked).
navigator.permissions.query({ name: "geolocation" }).then((result) => {
// result.state is "granted", "prompt", or "denied"
console.log(`Geolocation permission: ${result.state}`);
});Continuous position monitoring
For real-time tracking, watchPosition() calls your success callback every time the device's position changes. It returns a numeric watch ID that you pass to clearWatch() to stop tracking — failing to clear it keeps the location active and drains the battery.
const watchID = navigator.geolocation.watchPosition(success, error, options);
// success() now fires every time the position updates.
// Later, when tracking is no longer needed:
navigator.geolocation.clearWatch(watchID);If your tracking depends on the screen rotating between portrait and landscape, the Screen Orientation API pairs well with geolocation in mapping apps.
A complete example: show your location on a map
This example uses the Geolocation API to obtain your coordinates and the Leaflet.js library to render them on an OpenStreetMap layer.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Your Location on a Map</title>
<link
rel="stylesheet"
href="https://unpkg.com/[email protected]/dist/leaflet.css"
/>
</head>
<body>
<h1>Your Location on a Map</h1>
<div id="map" style="height: 400px"></div>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const map = L.map("map").setView([lat, lon], 13);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution: "© OpenStreetMap contributors",
}).addTo(map);
L.marker([lat, lon])
.addTo(map)
.bindPopup("You are here!")
.openPopup();
});
} else {
document.getElementById("map").textContent =
"Geolocation is not supported by your browser.";
}
});
</script>
</body>
</html>When you load the page, it will immediately request your location and then display a marker on the map at your position with a popup saying "You are here!" This visual representation helps you understand how websites can interact with geographic data to enhance user experiences.
Best practices
- Always feature-detect and serve over HTTPS, or every call will fail.
- Request location only when the user expects it — for example, after they click a "Find me" button — so the permission prompt has clear context.
- Handle every error code and show a helpful fallback (such as a manual location search) when permission is denied.
- Call
clearWatch()as soon as you no longer need continuous updates to save battery. - Pick options deliberately: high accuracy for navigation, a non-zero
maximumAgefor fast "near me" lookups.
Conclusion
The Geolocation API gives web apps a privacy-conscious way to read the user's location through three methods: getCurrentPosition() for a one-time reading, watchPosition() for live tracking, and clearWatch() to stop. Combined with thoughtful option choices and proper error handling, it powers maps, local search, and other location-aware features. To go further with related browser APIs, explore the Screen Orientation API and the Browser environment, specs chapter.