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
function getCurrentPosition(options = {}) {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error("Geolocation not supported"));
return;
}
navigator.geolocation.getCurrentPosition(resolve, reject, {
enableHighAccuracy: false,
timeout: 10_000,
maximumAge: 60_000,
...options,
});
});
}
try {
const pos = await getCurrentPosition();
const { latitude, longitude } = pos.coords;
console.log(latitude, longitude, "accuracy m", pos.coords.accuracy);
} catch (err) {
console.error(err.code, err.message);
}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)
function toRad(deg) {
return (deg * Math.PI) / 180;
}
function distanceKm(lat1, lon1, lat2, lon2) {
const R = 6371;
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) ** 2 +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
console.log(distanceKm(40.71, -74.0, 34.05, -118.24).toFixed(1), "km");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.