HTMLGeolocation API

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

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

1 (PERMISSION_DENIED)

The user (or browser policy) blocked the request

2 (POSITION_UNAVAILABLE)

Location information is not available right now

3 (TIMEOUT)

The request took longer than the configured timeout

HTTPS Is Required
Secure context only
Modern browsers only expose the Geolocation API on pages served over 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

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

enableHighAccuracy

Requests the most precise position possible (e.g. GPS), at the cost of speed and battery

timeout

Milliseconds to wait before failing with a TIMEOUT error

maximumAge

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

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)
Stop watching when the user leaves
Always call 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.

Accuracy is approximate
The `accuracy` value on 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

getCurrentPosition(success, error, options)

One-time location lookup

watchPosition(success, error, options)

Continuous location updates, returns a watch ID

clearWatch(id)

Stops a watchPosition subscription