项目中需要获取定位信息,js 提供了对于的接口去获取,整体可以分为以下几步
前置检查
通过判断 navigator
是否具有 geolocation
这个属性来判断是否支持获取定位信息
1 2 3
| function checkGeolocation() { return 'geolocation' in navigator }
|
权限校验
通过接口获取当前浏览器的定位授权状态
1 2 3 4
| async function checkPermission() { const res = await navigator?.permissions?.query({ name: 'geolocation' }) return res?.state || 'prompt' }
|
授权状态共有 denied
、granted
、prompt
三种状态
denied
:拒绝授权
granted
: 已经授权
prompt
:需要用户手动授权
获取位置
一次获取位置
1
| navigator.geolocation.getCurrentPosition(callback, handleError, options)
|
监听位置变化
1 2 3 4 5 6 7 8 9
| const geoWatchID = navigator.geolocation.watchPosition( callback, handleError, options )
navigator.geolocation.clearWatch(geoWatchID)
|
参数
callback
获取位置信息后的回调,类型为 (position: GeolocationPosition) => void
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| interface GeolocationCoordinates { readonly accuracy: number readonly altitude: number | null readonly altitudeAccuracy: number | null readonly heading: number | null readonly latitude: number readonly longitude: number readonly speed: number | null }
interface GeolocationPosition { readonly coords: GeolocationCoordinates readonly timestamp: EpochTimeStamp }
|
handleError
获取位置信息失败的回调,类型为 (error: GeolocationPositionError) => void
1 2 3 4 5 6 7 8 9 10
| interface GeolocationPositionError {
readonly code: number readonly message: string }
|
options
1 2 3 4 5
| interface PositionOptions { enableHighAccuracy?: boolean maximumAge?: number timeout?: number }
|
注意
iOS
或部分 Android
设备需要当前页面为 HTTPS
才被允许获取位置信息
- 可以通过当前页面检测设备是否支持获取位置信息
参考