JavaScript Geolocation API
The Geolocation API lets your web application access the user's real-world geographic location — latitude, longitude, altitude, and speed — directly from the browser, with a single permission prompt and no external library.
getCurrentPosition()coords object explainedwatchPosition()
What Is the Geolocation API?
The Geolocation API is a W3C standard browser interface
that allows web pages to request the user's geographical position. It is exposed through the
read-only property navigator.geolocation and requires
explicit user consent before any coordinates are shared.
The browser can determine location using one or more of the following sources, depending on device capabilities:
https://) or localhost.
On plain HTTP the permission will be blocked or permanently denied.
Checking for Browser Support
Always verify that navigator.geolocation
exists before calling any method. This is a feature check — it does not test whether
the user has granted permission.
// Feature detection — always do this first
if ("geolocation" in navigator) {
console.log("✓ Geolocation is supported");
// safe to call geolocation methods
} else {
console.log("✗ Geolocation is NOT supported");
// show a fallback UI or message
}
getCurrentPosition()
navigator.geolocation.getCurrentPosition()
is the primary method. It fires the success callback once with a
GeolocationPosition object when the device's position is
determined.
GeolocationPosition object
containing coords and timestamp.GeolocationPositionError with code and message.
PositionOptions object to control
accuracy, timeout, and cache age.navigator.geolocation.getCurrentPosition(
// ✅ Success callback
function(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const acc = position.coords.accuracy; // metres
const time = position.timestamp; // ms since epoch
console.log(`📍 Lat: ${lat}, Lon: ${lon}`);
console.log(`🎯 Accuracy: ±${acc} m`);
},
// ❌ Error callback
function(error) {
console.error("Location error:", error.message);
}
);
The coords Object
The position.coords property is a
GeolocationCoordinates object with seven read-only
properties. latitude, longitude,
and accuracy are always present. The rest may be
null depending on the device:
| Property | Type | Unit | Always present? | Description |
|---|---|---|---|---|
latitude |
Number | Degrees |
|
Geographic latitude (−90 to +90) |
longitude |
Number | Degrees |
|
Geographic longitude (−180 to +180) |
accuracy |
Number | Metres |
|
Radius of lat/lon confidence circle |
altitude |
Number | null | Metres |
|
Height above WGS84 reference ellipsoid |
altitudeAccuracy |
Number | null | Metres |
|
Accuracy of the altitude value |
heading |
Number | null | Degrees |
|
Direction of travel (0 = North, clockwise). NaN if speed = 0. |
speed |
Number | null | m/s |
|
Magnitude of device velocity |
navigator.geolocation.getCurrentPosition((position) => {
const {
latitude, longitude, accuracy,
altitude, altitudeAccuracy,
heading, speed
} = position.coords;
console.log(`Lat / Lon : ${latitude.toFixed(6)}, ${longitude.toFixed(6)}`);
console.log(`Accuracy : ±${accuracy.toFixed(1)} m`);
if (altitude !== null) {
console.log(`Altitude : ${altitude.toFixed(1)} m`);
}
if (speed !== null) {
// Convert m/s → km/h
console.log(`Speed : ${(speed * 3.6).toFixed(1)} km/h`);
}
const readableTime = new Date(position.timestamp).toLocaleString();
console.log(`Timestamp : ${readableTime}`);
});
Error Handling
The error callback receives a GeolocationPositionError
object. Always handle all three error codes — users regularly deny location access, especially
on desktop.
| code | Constant | When it fires |
|---|---|---|
1 |
PERMISSION_DENIED |
User clicked "Block" or the browser policy denies access |
2 |
POSITION_UNAVAILABLE |
Location hardware / network source returned an error |
3 |
TIMEOUT |
Acquisition exceeded the timeout option |
function handleGeoError(error) {
const messages = {
1: "Permission denied. Please allow location in your browser settings.",
2: "Position unavailable. Check device sensors or network.",
3: "Request timed out. Try again."
};
const msg = messages[error.code] || `Unknown error: ${error.message}`;
console.error(`[Geo error ${error.code}] ${msg}`);
// Show user-friendly UI
document.getElementById("geoStatus").textContent = msg;
}
navigator.geolocation.getCurrentPosition(
(pos) => console.log(pos.coords),
handleGeoError
);
PositionOptions
All three geolocation methods accept an optional
PositionOptions object as the third argument, letting you
balance accuracy, speed, and battery life:
| Option | Type | Default | Description |
|---|---|---|---|
enableHighAccuracy |
Boolean | false |
Hint to use GPS if available — slower and drains more battery. |
timeout |
Number | Infinity |
Max milliseconds the browser may take to return a position before triggering error code 3. |
maximumAge |
Number | 0 |
Max age (ms) of a cached position the browser may return. 0 =
always fresh. Infinity = always use cache. |
const options = {
enableHighAccuracy: true, // prefer GPS over Wi-Fi / IP
timeout: 10000, // give up after 10 seconds
maximumAge: 30000 // re-use a fix ≤ 30 s old
};
navigator.geolocation.getCurrentPosition(
(pos) => console.log("Coords:", pos.coords),
(err) => console.error("Error:", err.message),
options // ← third argument
);
maximumAge: 60000 combined with
enableHighAccuracy: false for non-real-time use cases (e.g.
showing a city-level weather forecast). This avoids waking the GPS chip on every call.
watchPosition()
Unlike getCurrentPosition(), which fires
once, watchPosition() keeps firing the success callback
every time the device position changes. It returns a numeric
watchId that you must store to stop the watch later.
let watchId; // store the ID so we can stop later
function startTracking() {
watchId = navigator.geolocation.watchPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords;
console.log(`🔄 Update → ${latitude.toFixed(6)}, ${longitude.toFixed(6)}`);
updateMapMarker(latitude, longitude); // your map function
},
(err) => console.error(err.message),
{ enableHighAccuracy: true, timeout: 5000 }
);
console.log(`Watch started with ID: ${watchId}`);
}
clearWatch()
Call navigator.geolocation.clearWatch(watchId)
to stop continuous tracking. Always call this when the user navigates away or when location is
no longer needed — an active watch keeps the GPS radio alive and drains battery.
function stopTracking() {
if (watchId !== undefined) {
navigator.geolocation.clearWatch(watchId);
console.log(`Watch ${watchId} cleared.`);
watchId = undefined;
}
}
// ✅ Good practice — clean up before user leaves the page
window.addEventListener("beforeunload", stopTracking);
// ✅ In React — clean up inside useEffect return
useEffect(() => {
const id = navigator.geolocation.watchPosition(onSuccess, onError);
return () => navigator.geolocation.clearWatch(id); // cleanup
}, []);
Real-World Map Integration (Leaflet.js)
The most common Geolocation use case is rendering the user's position on an interactive map. Leaflet.js is a free, open-source mapping library that pairs perfectly with the Geolocation API.
<!-- 1. Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<!-- 2. Map container -->
<div id="map" style="height:420px; border-radius:12px;"></div>
<!-- 3. Leaflet JS -->
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
// 1. Initialise map at a world-level default view
const map = L.map("map").setView([20, 78], 5);
// 2. Add OpenStreetMap tiles (free, no API key needed)
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: "© <a href='https://openstreetmap.org'>OpenStreetMap</a> contributors"
}).addTo(map);
// 3. Get position and fly to it
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((pos) => {
const { latitude: lat, longitude: lon, accuracy } = pos.coords;
// Smooth pan + zoom to user location
map.flyTo([lat, lon], 15, { duration: 1.5 });
// Drop a marker with a popup
L.marker([lat, lon])
.addTo(map)
.bindPopup("📍 You are here!")
.openPopup();
// Draw an accuracy circle around the fix
L.circle([lat, lon], {
radius: accuracy,
color: "#f7df1e",
fillOpacity: 0.1
}).addTo(map);
}, (err) => console.error(err.message), { enableHighAccuracy: true });
}
Try It Yourself
Edit the code below and click ▶ Run Code to see Geolocation + Leaflet running live. Click Run in Editor for a full-screen editor window.
Best Practices
- Check
"geolocation" in navigatorfirst - Always provide an error callback
- Serve over HTTPS in production
- Call
clearWatch()when done - Use
maximumAgeto avoid re-querying GPS - Only request location on a user gesture (button click), not page load
- Show a loading indicator while acquiring position
- Handle all three error codes with a user-friendly message
- Request location on page load without interaction
- Ignore the error callback
- Store raw coordinates without user awareness
- Use
enableHighAccuracy: truewhen low accuracy is sufficient - Leave a
watchPositionrunning indefinitely in SPAs - Assume
altitude,speed, orheadingare never null
Which Geolocation error code fires when the user clicks "Block"?
- The Geolocation API lives at
navigator.geolocationand requires HTTPS + user permission. getCurrentPosition(success, error, options)retrieves the position once.watchPosition()fires the callback on every position change and returns a watchId.- Always call
clearWatch(watchId)to stop tracking and save battery. - The
coordsobject provideslatitude,longitude, andaccuracy(always), plus optionalaltitude,speed, andheading. - Three error codes:
1PERMISSION_DENIED ·2POSITION_UNAVAILABLE ·3TIMEOUT. - Use
enableHighAccuracy,timeout, andmaximumAgeinPositionOptionsto balance accuracy and battery.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.