跳到主要内容

useGeolocation

分类
导出大小
553 B
上次更改
8 个月前

响应式的 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
>

来源

源代码演示文档

贡献者

Anthony Fu
Antério Vieira
Jelf
IlyaL
SerKo
IlyaL
Anthony Fu
丶远方
vaakian X
Enric Bisbe Gil
Egor Startsev
Michael J. Roberts
Shinigami
wheat
Alex Kozack
Sanxiaozhizi

更新日志

8c521 - feat(components)!: 重构组件并使其保持一致 (#4912)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。