Lzh on GitHub

响应式 地理定位 API 允许用户在需要时向网络应用程序提供他们的位置。出于隐私考虑,系统会征求用户许可才能报告位置信息。

Demo

使用

import { useGeolocation } from '@vueuse/core'

const { coords, locatedAt, error, resume, pause } = useGeolocation()
状态类型描述
coordsCoordinates有关检索到的位置信息,例如纬度和经度
locatedAtDate上次地理定位调用的时间。
errorstring如果地理定位 API 失败,则显示错误消息
resumefunction控制函数,用于恢复地理位置更新
pausefunction控制函数,用于暂停地理位置更新

配置

useGeolocation 函数接受 PositionOptions 对象作为可选参数。

组件方式使用

此函数也通过 @vueuse/components 包提供一个无渲染组件版本。了解更多用法

<template>
  <UseGeolocation v-slot="{ coords: { latitude, longitude } }">
    Latitude: {{ latitude }}
    Longitude: {{ longitude }}
  </UseGeolocation>
</template>

类型声明

export interface UseGeolocationOptions
  extends Partial<PositionOptions>,
    ConfigurableNavigator {
  immediate?: boolean
}
/**
 * Reactive Geolocation API.
 *
 * @see https://vueuse.org/useGeolocation
 * @param options
 */
export declare function useGeolocation(options?: UseGeolocationOptions): {
  isSupported: ComputedRef<boolean>
  coords: Ref<
    {
      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
    },
    | Omit<GeolocationCoordinates, "toJSON">
    | {
        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
      }
  >
  locatedAt: ShallowRef<number | null, number | null>
  error: ShallowRef<
    GeolocationPositionError | null,
    GeolocationPositionError | null
  >
  resume: () => void
  pause: () => void
}
export type UseGeolocationReturn = ReturnType<typeof useGeolocation>