Geolocation API
The Geolocation API lets a web page ask the browser for the user's current physical location — useful for store locators, weather apps, mapping, and delivery estimates. Because location is sensitive personal data, the API is permission-gated and only available in secure contexts.
Getting the Current Position
get-current-position.js
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords
console.log(`Lat: ${latitude}, Lng: ${longitude}, Accuracy: ${accuracy}m`)
},
(error) => {
console.error('Geolocation failed:', error.message)
}
)
} else {
console.log('Geolocation is not supported by this browser')
}Lat: 37.7749, Lng: -122.4194, Accuracy: 20m
The Permission Prompt
Calling getCurrentPosition triggers a native browser prompt
asking the user to allow or deny access to their location. Your success and
error callbacks fire based on the user's choice — there is no way to read
location silently or skip the prompt.
The prompt only appears the first time (per site) unless the user resets permissions.
If the user denies access, the error callback fires with
error.code === error.PERMISSION_DENIED.Browsers may remember a denial and stop showing the prompt again, silently failing on future calls.
error.code | Meaning |
|---|---|
| The user (or browser policy) blocked the request |
| Location information is not available right now |
| The request took longer than the configured |
HTTPS Is Required
https:// (or localhost during development). On a plain http:// page, getCurrentPosition either fails immediately or is not available at all.Options: Accuracy, Timeout, and Caching
getCurrentPosition accepts a third, optional options object
that lets you trade off accuracy against speed and battery usage.
geolocation-options.js
navigator.geolocation.getCurrentPosition(
onSuccess,
onError,
{
enableHighAccuracy: true, // use GPS if available, uses more battery
timeout: 10000, // give up after 10 seconds
maximumAge: 60000, // accept a cached position up to 60s old
}
)Option | Effect |
|---|---|
| Requests the most precise position possible (e.g. GPS), at the cost of speed and battery |
| Milliseconds to wait before failing with a |
| Milliseconds of staleness allowed for a cached position instead of requesting a fresh one |
Watching Position Over Time
For live tracking (e.g. a moving map), use{' '}
watchPosition instead of a single{' '}
getCurrentPosition call. It keeps calling your callback as the
device moves, and returns a watch ID you can pass to{' '}
clearWatch to stop.
watch-position.js
const watchId = navigator.geolocation.watchPosition((position) => {
updateMapMarker(position.coords.latitude, position.coords.longitude)
})
// Later, when tracking is no longer needed
navigator.geolocation.clearWatch(watchId)clearWatch when a component unmounts or the user navigates away from a tracking view — an open watch keeps the GPS active and drains battery unnecessarily.Privacy Considerations
Only request location when it directly benefits the current task — asking on page load with no context feels invasive and often gets denied.
Explain, in the UI, why you need location before triggering the browser prompt (a short message near a button works well).
Never store precise location data longer than necessary, and be explicit in your privacy policy about how it is used.
Provide a graceful fallback (e.g. manual city/zip entry) for users who decline the prompt.
position.coords is a radius in meters, not a guarantee — actual precision depends on GPS, Wi-Fi positioning, or IP-based estimation, and varies a lot between devices and environments.Quick Reference
Method | Purpose |
|---|---|
| One-time location lookup |
| Continuous location updates, returns a watch ID |
| Stops a |