geolocation
Read the device's location, once or as a continuous watch, via the Geolocation API.
Import: @rtorcato/browser-common/geolocation
๐ MDN: Geolocation API ยท ๐ caniuse: geolocation
Requires a secure context (HTTPS, or localhost in dev) and prompts the
user for permission on first use.
Browser supportโ
| API | Chrome | Edge | Firefox | Safari | iOS Safari | Baseline |
|---|---|---|---|---|---|---|
Geolocation.getCurrentPosition | โ 5+ | โ 12+ | โ 3.5+ | โ 5+ | โ โค3+ | Widely available |
Geolocation.watchPosition | โ 5+ | โ 12+ | โ 3.5+ | โ 5+ | โ โค3+ | Widely available |
Needs: secure context (HTTPS)
โ
supported ยท โ partial ยท โ not supported ยท [n] see note. Generated from MDN browser-compat-data and web-features. caniuse: Geolocation.getCurrentPosition ยท Geolocation.watchPosition
Exampleโ
import {
isGeolocationAvailable,
getCurrentPosition,
watchPosition,
clearWatch,
} from '@rtorcato/browser-common/geolocation'
if (isGeolocationAvailable()) {
const position = await getCurrentPosition({ enableHighAccuracy: true })
console.log(position.coords.latitude, position.coords.longitude)
const watchId = watchPosition((p) => updateMap(p.coords))
// later:
if (watchId !== undefined) clearWatch(watchId)
}
Exportsโ
isGeolocationAvailable()โ feature checkgetCurrentPosition(options?)โ resolve a singleGeolocationPositionwatchPosition(success, error?, options?)โ subscribe to updates; returns a watch idclearWatch(id)โ stop a watch
See the API reference for full signatures.