Skip to content

useGeolocation

获取和监听设备的地理位置信息。

前置依赖

依赖参数

参数名类型说明
deps.vue.ref<T>(value: T) => Ref<T>Vue ref 函数
deps.vue.onMounted(fn: () => void) => voidVue onMounted 钩子
deps.vue.onUnmounted(fn: () => void) => voidVue onUnmounted 钩子
deps.geolocationGeolocation地理位置 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
}

参数

参数名类型必填说明
optionsGeolocationOptions配置选项
options.enableHighAccuracyboolean是否启用高精度定位(默认 false)
options.timeoutnumber超时时间(毫秒)
options.maximumAgenumber位置缓存时间(毫秒)
options.immediateboolean是否在组件挂载时立即获取位置
depsUseGeolocationDeps依赖注入对象

返回值

属性类型说明
isSupportedRef<boolean>是否支持地理位置 API
coordsRef<GeolocationPosition['coords'] | null>当前坐标(经纬度、精度等)
timestampRef<number | null>定位时间戳
isLocatingRef<boolean>是否正在定位
errorRef<string | null>错误信息
getCurrentPosition() => Promise<void>获取当前位置
watchPosition() => void开始监听位置变化
clearWatch() => void停止监听位置变化

工作原理

  1. 检查浏览器是否支持地理位置 API
  2. 根据配置选项调用 getCurrentPositionwatchPosition
  3. 成功获取位置后更新 coordstimestamp
  4. 失败时更新 error 状态
  5. 组件卸载时自动清理监听

坐标对象包含:

  • latitude - 纬度
  • longitude - 经度
  • accuracy - 精度(米)
  • altitude - 海拔(米,可能为 null)
  • altitudeAccuracy - 海拔精度(米,可能为 null)
  • heading - 方向(度,可能为 null)
  • speed - 速度(米/秒,可能为 null)