Geolocation API in JavaScript
Introduction
The Geolocation API reads the device’s approximate position (with user permission) for maps, local search, and check-ins. Access is through navigator.geolocation in secure contexts (HTTPS). This chapter covers one-shot reads, watching position, and handling errors responsibly.
Prerequisites
Permission and Privacy
- Browsers show a permission prompt—never assume location is available
- Explain why you need location in UI copy before calling the API
- Prefer coarse location when precise GPS is unnecessary
Warning
Location data is sensitive. Send it only to servers you trust over HTTPS; follow privacy laws (GDPR, etc.) in production apps.
One-Shot Position with Promise Wrapper
Error Codes
| Code | Meaning |
|---|---|
| 1 | Permission denied |
| 2 | Position unavailable |
| 3 | Timeout |
Watch Position (Updates)
// watchId — call clearWatch when done
const watchId = navigator.geolocation.watchPosition(
(pos) => {
console.log("update", pos.coords.latitude, pos.coords.longitude);
},
(err) => console.error(err.message),
{ enableHighAccuracy: true, maximumAge: 0 }
);
// later: navigator.geolocation.clearWatch(watchId);Drains battery on mobile—stop watching when leaving the screen.
Display on a Map (Concept)
Most apps send coordinates to Mapbox, Google Maps, or Leaflet—API keys and tiles are provider-specific. Your job in JS is reliable coords + error UI.
Fallback When Denied
async function locateOrDefault() {
try {
const pos = await getCurrentPosition();
return { lat: pos.coords.latitude, lng: pos.coords.longitude };
} catch {
return { lat: 40.7128, lng: -74.006, label: "default NYC" };
}
}
console.log(await locateOrDefault());Mini Example: Distance Stub (Haversine)
FAQ
Works on HTTP localhost?
Often yes for localhost; production needs HTTPS.
IP-based geolocation?
Server-side IP lookup is separate—less accurate than GPS.
Relation to Navigation?
Navigation changes URLs; geolocation reads physical coordinates—different APIs.