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
| Property | Meaning |
|---|---|
coords.latitude | Degrees north (positive) or south (negative). |
coords.longitude | Degrees east (positive) or west (negative). |
coords.accuracy | Reported accuracy in metres. |
coords.altitude | Metres above sea level (if available). |
coords.speed | Speed in m/s (if moving). |
timestamp | When 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);
11 letters. Lives on navigator.
Discussion
Loading…