useGeolocation
获取和监听设备的地理位置信息。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.vue.ref | <T>(value: T) => Ref<T> | Vue ref 函数 |
deps.vue.onMounted | (fn: () => void) => void | Vue onMounted 钩子 |
deps.vue.onUnmounted | (fn: () => void) => void | Vue onUnmounted 钩子 |
deps.geolocation | Geolocation | 地理位置 API |
环境要求
浏览器 API: Geolocation API
需要在 HTTPS 环境下使用,或在 localhost 开发环境中测试。
函数签名
typescript
function useGeolocation(
options: GeolocationOptions,
deps: UseGeolocationDeps
): UseGeolocationReturn
interface GeolocationOptions {
enableHighAccuracy?: boolean // 是否启用高精度
timeout?: number // 超时时间(毫秒)
maximumAge?: number // 缓存时间(毫秒)
immediate?: boolean // 是否立即获取位置
}
interface UseGeolocationDeps {
vue: VueCompositionAPI
geolocation: Geolocation
}
interface UseGeolocationReturn {
isSupported: Ref<boolean>
coords: Ref<GeolocationPosition['coords'] | null>
timestamp: Ref<number | null>
isLocating: Ref<boolean>
error: Ref<string | null>
getCurrentPosition: () => Promise<void>
watchPosition: () => void
clearWatch: () => void
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
options | GeolocationOptions | 否 | 配置选项 |
options.enableHighAccuracy | boolean | 否 | 是否启用高精度定位(默认 false) |
options.timeout | number | 否 | 超时时间(毫秒) |
options.maximumAge | number | 否 | 位置缓存时间(毫秒) |
options.immediate | boolean | 否 | 是否在组件挂载时立即获取位置 |
deps | UseGeolocationDeps | 是 | 依赖注入对象 |
返回值
| 属性 | 类型 | 说明 |
|---|---|---|
isSupported | Ref<boolean> | 是否支持地理位置 API |
coords | Ref<GeolocationPosition['coords'] | null> | 当前坐标(经纬度、精度等) |
timestamp | Ref<number | null> | 定位时间戳 |
isLocating | Ref<boolean> | 是否正在定位 |
error | Ref<string | null> | 错误信息 |
getCurrentPosition | () => Promise<void> | 获取当前位置 |
watchPosition | () => void | 开始监听位置变化 |
clearWatch | () => void | 停止监听位置变化 |
工作原理
- 检查浏览器是否支持地理位置 API
- 根据配置选项调用
getCurrentPosition或watchPosition - 成功获取位置后更新
coords和timestamp - 失败时更新
error状态 - 组件卸载时自动清理监听
坐标对象包含:
latitude- 纬度longitude- 经度accuracy- 精度(米)altitude- 海拔(米,可能为 null)altitudeAccuracy- 海拔精度(米,可能为 null)heading- 方向(度,可能为 null)speed- 速度(米/秒,可能为 null)