useGeolocation
响应式的 Geolocation API。如果用户愿意,它允许用户向 Web 应用程序提供他们的位置。出于隐私原因,系统会请求用户许可报告位置信息。
演示
{
"coords": {
"accuracy": 0,
"latitude": null,
"longitude": null,
"altitude": null,
"altitudeAccuracy": null,
"heading": null,
"speed": null
},
"locatedAt": null,
"error": null
}用法
ts
import { useGeolocation } from '@vueuse/core'
const { coords, locatedAt, error, resume, pause } = useGeolocation()| 状态 | 类型 | 描述 |
|---|---|---|
| coords | 坐标 | 检索到的位置信息,例如纬度和经度 |
| locatedAt | 日期 | 上次地理定位调用的时间 |
| error | 字符串 | 如果地理定位 API 失败,则显示错误消息。 |
| resume | 函数 | 控制函数,用于恢复更新地理位置 |
| pause | 函数 | 控制函数,用于暂停更新地理位置 |
配置
useGeolocation 函数将 PositionOptions 对象作为可选参数。
组件用法
此函数还通过
@vueuse/components包提供了一个无渲染组件版本。了解更多用法。
vue
<template>
<UseGeolocation v-slot="{ coords: { latitude, longitude } }">
Latitude: {{ latitude }}
Longitude: {{ longitude }}
</UseGeolocation>
</template>类型声明
显示类型声明
ts
export interface UseGeolocationOptions
extends Partial<PositionOptions>,
ConfigurableNavigator {
immediate?: boolean
}
/**
* Reactive Geolocation API.
*
* @see https://vueuse.org.cn/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>