Web Geolocation API
The Geolocation API tells you the device's coordinates — once or repeatedly. Always require user consent and degrade gracefully when permission is denied.
One-shot read
JS
navigator.geolocation.getCurrentPosition(
(pos) => {
console.log(pos.coords.latitude, pos.coords.longitude);
console.log("accuracy", pos.coords.accuracy, "m");
},
(err) => console.error(err.message),
{ enableHighAccuracy: true, timeout: 5000, maximumAge: 60_000 }
);
Subscribe to updates
JS
const id = navigator.geolocation.watchPosition( pos => updateMap(pos.coords), err => toast(err.message), ); // Stop when done navigator.geolocation.clearWatch(id);
Coordinates object
| Field | Means |
|---|---|
latitude / longitude | WGS-84 coordinates. |
accuracy | Horizontal accuracy in metres. |
altitude / altitudeAccuracy | If available (GPS). |
heading | Direction of travel, 0–360°. |
speed | Metres per second. |
Errors
| Code | Meaning |
|---|---|
| 1 — PERMISSION_DENIED | User said no. |
| 2 — POSITION_UNAVAILABLE | No fix possible (indoors, airplane mode). |
| 3 — TIMEOUT | Took longer than your timeout option. |
Check permission without prompting
JS
const status = await navigator.permissions.query({ name: "geolocation" });
if (status.state === "denied") showFallbackLocationPicker();
Privacy: Browsers only expose Geolocation over HTTPS (and on
localhost). Prompt only after the user clicks a "Use my location" button — not on page load.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from Web Geolocation API!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Read the device location once.
navigator.
.getCurrentPosition(onOk, onErr);
Eleven letters.
Discussion
Loading…