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

HTML Geolocation

The Geolocation API asks the browser for the user's latitude and longitude. The user is always shown a permission prompt first.

Reading the position

navigator.geolocation.getCurrentPosition(
    function (pos) {
        console.log(pos.coords.latitude, pos.coords.longitude);
    },
    function (err) {
        console.error('Denied or unavailable:', err.message);
    }
);

What you get

PropertyMeaning
coords.latitudeDegrees north (positive) or south (negative).
coords.longitudeDegrees east (positive) or west (negative).
coords.accuracyReported accuracy in metres.
coords.altitudeMetres above sea level (if available).
coords.speedSpeed in m/s (if moving).
timestampWhen the position was read.

Watching position

Use watchPosition when you need continuous updates (e.g. live tracking):

const id = navigator.geolocation.watchPosition(onMove);
// Later: navigator.geolocation.clearWatch(id);
Privacy + security: Geolocation only works in a secure context (HTTPS or localhost). The user must approve every origin, and they can revoke permission at any time.

Example

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML Geolocation</title>
</head>
<body>

<h1>HTML Geolocation</h1>
<p>This is a demo page for the "HTML Geolocation" lesson.</p>

</body>
</html>
Try it Yourself »

Exercise

Name the API object that exposes the user location.

navigator. .getCurrentPosition(cb);

Test yourself

Q1. Geolocation runs only over…
Q2. One-shot location read uses…
Q3. Continuous updates use…

Discussion

Loading…