Skip to content

useGeolocation

提供响应式的 Geolocation API。如果用户愿意,它允许用户向 Web 应用程序提供其位置。出于隐私原因,用户需要获得报告位置信息的权限。

使用方法

ts
import { useGeolocation } from '@vueuse/core'

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

配置

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

组件使用

vue
<template>
  <UseGeolocation v-slot="{ coords: { latitude, longitude } }">
    纬度:{{ latitude }} 经度:{{ longitude }}
  </UseGeolocation>
</template>

Type Declarations

ts
export interface UseGeolocationOptions
  extends Partial<PositionOptions>, ConfigurableNavigator {
  immediate?: boolean
}
export interface UseGeolocationReturn extends Supportable {
  coords: Ref<Omit<GeolocationPosition["coords"], "toJSON">>
  locatedAt: ShallowRef<number | null>
  error: ShallowRef<GeolocationPositionError | null>
  resume: () => void
  pause: () => void
}
/**
 * 响应式 Geolocation API.
 *
 * @see /useGeolocation
 * @param options
 */
export declare function useGeolocation(
  options?: UseGeolocationOptions,
): UseGeolocationReturn