useGeolocation
响应式 Geolocation API。它允许用户在愿意的情况下向 Web 应用程序提供他们的位置。出于隐私原因,会请求用户授权以报告位置信息。
演示
{
"coords": {
"accuracy": 0,
"latitude": null,
"longitude": null,
"altitude": null,
"altitudeAccuracy": null,
"heading": null,
"speed": null
},
"locatedAt": null,
"error": null
}
用法
js
import { useGeolocation } from '@vueuse/core'
const { coords, locatedAt, error, resume, pause } = useGeolocation()
状态 | 类型 | 描述 |
---|---|---|
coords | 坐标 | 检索到的位置信息,例如纬度和经度 |
locatedAt | Date | 上次地理定位调用的时间 |
error | string | 地理定位 API 失败时的错误消息。 |
resume | function | 恢复更新地理定位的控制函数 |
pause | function | 暂停更新地理定位的控制函数 |
配置
useGeolocation
函数接受 PositionOptions 对象作为可选参数。
组件用法
此函数还通过
@vueuse/components
包提供了一个无渲染组件版本。 了解更多关于用法的信息。
vue
<template>
<UseGeolocation v-slot="{ coords: { latitude, longitude } }">
Latitude: {{ latitude }}
Longitude: {{ longitude }}
</UseGeolocation>
</template>
类型声明
显示类型声明
typescript
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>
源代码
贡献者
更新日志
v12.0.0-beta.1
于 2024/11/21