iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FieldMeans
latitude / longitudeWGS-84 coordinates.
accuracyHorizontal accuracy in metres.
altitude / altitudeAccuracyIf available (GPS).
headingDirection of travel, 0–360°.
speedMetres per second.

Errors

CodeMeaning
1 — PERMISSION_DENIEDUser said no.
2 — POSITION_UNAVAILABLENo fix possible (indoors, airplane mode).
3 — TIMEOUTTook 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);

Test yourself

Q1. Geolocation works…
Q2. One-shot read uses…
Q3. `watchPosition` returns…

Discussion

Loading…