The Geolocation API: Permissions, Accuracy, Privacy
The browser knows where you are â approximately â and the Geolocation API is the only sanctioned way to ask. That framing matters more than the method signatures. Unlike most browser APIs, geolocation exposes genuinely sensitive information, so the platform gates it behind a permission prompt, restricts it to secure contexts, and in several jurisdictions sits inside a ring of consent regulation. A site that requests location the moment it loads trains users to click deny, and denial is sticky: browsers remember, and a denied origin rarely gets a second prompt.
Used well, geolocation powers store locators, delivery tracking, weather by current position, and fitness logging. This lesson covers the request surface, how to interpret the coordinates you receive, and the product-level decisions â when to ask, what to do on denial, how long to keep watching â that determine whether the feature helps or irritates.
Ask at a Moment of Clear Intent
The permission prompt should answer a question the user just asked themselves. Pressing a "Find stores near me" button is a natural trigger. Page load is not, because the user has not yet seen any value that would justify handing over their position. Browsers reinforce this: Chrome requires a secure context, and recent versions treat the geolocation permission as one that defaults to blocked for origins that have not previously been granted. Safari shows the prompt per session by default.
Build the UI as a two-step flow: explain what location will be used for in plain language, then trigger the API call from the click. If permission is denied, offer a manual alternative â a city picker, a postal code field â instead of a dead end. A store locator that only works with geolocation is a store locator that fails for every privacy-conscious and every corporate-network user.
getCurrentPosition and Its Options
The one-shot request takes a success callback, an error callback, and an options object:
function requestLocation() {
if (!('geolocation' in navigator)) {
showManualLocationFallback('Geolocation is not supported in this browser.');
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords;
showMapAt(latitude, longitude, accuracy);
reverseGeocode(latitude, longitude);
},
(error) => {
const messages = {
1: 'Location permission denied. Try entering a city instead.',
2: 'Your position is unavailable right now.',
3: 'The location request timed out. Please try again.'
};
showManualLocationFallback(messages[error.code] || 'Location failed.');
},
{
enableHighAccuracy: true,
timeout: 8000,
maximumAge: 60000
}
);
}
document.getElementById('find-near-me').addEventListener('click', requestLocation);
The three options pull in different directions. enableHighAccuracy asks for GPS-grade fixes where the platform offers them; it improves precision from city-block scale to meter scale but costs battery and time, often adding seconds on desktop where only network location exists. timeout caps how long the browser may spend hunting for a fix. maximumAge accepts a cached fix up to the given age in milliseconds, trading freshness for speed â sixty seconds is a reasonable default for a store locator, while a turn-by-turn view wants zero.
What the Position Object Actually Contains
The success callback receives a Position with a timestamp and a coords object. Only some fields are populated, and the ones that matter most are the ones people ignore:
| Field | Meaning | Availability |
|---|---|---|
| latitude, longitude | Degrees, WGS84 datum | Always |
| accuracy | Horizontal radius in meters, 68% confidence | Always |
| altitude | Meters above the WGS84 ellipsoid | Device dependent |
| altitudeAccuracy | Vertical accuracy in meters | Device dependent |
| heading | Degrees from true north, 0 is stationary | Moving devices only |
| speed | Meters per second | Moving devices only |
Treat accuracy as a first-class part of the UX, not noise. A fix with a two-hundred-meter radius should not claim the user is "at" a specific store; render a translucent circle around the position instead of a pin, and only zoom to street level when accuracy drops below roughly fifty meters. Silent rounding of imprecise data into confident UI is how delivery apps end up insisting a customer is standing in a river.
watchPosition for Continuous Tracking
When the user is in motion â a delivery driver, a jogger, a hiker on a trail â one-shot requests are the wrong shape. watchPosition fires the success callback on every meaningful change and returns an id you pass to clearWatch to stop:
let watchId = null;
const track = [];
function haversineMeters(a, b) {
const toRad = (deg) => (deg * Math.PI) / 180;
const earthRadius = 6371000;
const dLat = toRad(b.latitude - a.latitude);
const dLon = toRad(b.longitude - a.longitude);
const lat1 = toRad(a.latitude);
const lat2 = toRad(b.latitude);
const h =
Math.sin(dLat / 2) ** 2 +
Math.sin(dLon / 2) ** 2 * Math.cos(lat1) * Math.cos(lat2);
return 2 * earthRadius * Math.asin(Math.sqrt(h));
}
function startTracking() {
if (watchId !== null) return;
watchId = navigator.geolocation.watchPosition(
(position) => {
const { latitude, longitude, accuracy, speed } = position.coords;
const previous = track[track.length - 1];
if (previous && haversineMeters(previous, { latitude, longitude }) < accuracy) {
return;
}
track.push({ latitude, longitude });
updateRoute(track);
if (speed !== null) updateSpeedometer(speed * 3.6);
},
(error) => console.warn('Tracking error', error.code),
{ enableHighAccuracy: true, maximumAge: 0, timeout: 15000 }
);
}
function stopTracking() {
if (watchId !== null) {
navigator.geolocation.clearWatch(watchId);
watchId = null;
}
}
window.addEventListener('pagehide', stopTracking);
The distance filter is the detail that separates a battery-conscious tracker from a wasteful one: GPS jitter produces fixes that differ by meters while the user stands still, and pushing every jitter fix through a network call burns data and power for nothing. Ignore any new point whose displacement is smaller than the fix's own accuracy radius. And always stop watching when the page is hidden or the flow ends â a forgotten watch keeps the GPS radio warm for a page the user is no longer looking at.
Privacy, Retention, and Regulation
Location data is personal data under GDPR, CCPA, and most sibling statutes. Collect only what the feature needs, keep it only as long as needed, and be able to delete it on request. Precision is a consent lever: if your use case tolerates city-level placement, say so, and consider rounding coordinates server-side before storage. Never transmit raw continuous tracks to analytics pipelines that were designed for page-view events â the retention defaults there were not written with breadcrumb trails in mind.
Disclose the purpose at the moment of the prompt and again in the privacy policy. A "find nearby stores" promise that quietly becomes "we built a movement profile" is a dark pattern with regulatory teeth.
Checking Permission State Before Prompting
The Permissions API exposes the current geolocation permission as a queryable state, which lets you tailor the UI before ever triggering a prompt:
async function geolocationState() {
if (!navigator.permissions || !navigator.permissions.query) {
return 'unknown';
}
try {
const status = await navigator.permissions.query({ name: 'geolocation' });
return status.state; // 'granted', 'denied', or 'prompt'
} catch {
return 'unknown';
}
}
geolocationState().then((state) => {
if (state === 'granted') {
document.getElementById('find-near-me').hidden = false;
} else if (state === 'denied') {
showManualLocationFallback('Location is blocked in your browser settings.');
}
});
Not every browser accepts the geolocation permission name in query, so wrap the call defensively as shown and fall back to a normal request when it throws. The value is in the denied branch: you can skip a prompt that would certainly be dismissed and lead the user straight to the manual path.
When Location Is Simply Unavailable
Denial, timeouts, and offline devices are normal operating conditions, not exceptions. Provide the manual path â postal code, city search, or a map the user can pan â and persist the choice so returning visitors are not re-prompted. IP-based geolocation is a coarse fallback you can offer without any client permission at all, with the caveat that it resolves to an ISP endpoint that may be hundreds of kilometers away. State the assumption in the UI when you use it, and keep the manual override visible.
Common Mistakes
Requesting geolocation on page load
Fix: Ask from a user gesture with a visible explanation of why the location is needed.
Ignoring the accuracy field and drawing a precise pin
Fix: Render accuracy as a radius circle and only zoom in when the radius is small.
Never calling clearWatch after starting watchPosition
Fix: Stop the watch on pagehide, when the flow completes, and when the user pauses tracking.
Sending every jitter fix to the server
Fix: Filter points by displacement relative to accuracy before recording or transmitting.
Offering no fallback after a denial
Fix: Provide postal-code or city search so the feature still works without location.
Best Practices
- Trigger the request from a labeled button and explain the purpose in the interface before the prompt appears.
- Match enableHighAccuracy to the task: true for navigation, false for city-level discovery.
- Cache fixes with a sensible maximumAge so repeated views of the same page do not re-query the GPS.
- Round or blur stored coordinates to the precision your feature actually needs.
Key Takeaways
- Location is sensitive data behind a permission wall â ask with clear intent, not on load.
- getCurrentPosition handles one-shot needs; watchPosition handles motion, and always needs a matching clearWatch.
- accuracy, speed, and heading are sparse and device-dependent â design UI that reflects uncertainty.
- enableHighAccuracy, timeout, and maximumAge trade precision against battery and latency.
- Denial and failure are normal paths; ship a manual fallback and a persistence layer for the user's choice.
- Regulation treats coordinates as personal data: minimize collection, shorten retention, honor deletion.