跳到内容

useGeolocation

类别
导出大小
558 B
最后更改
3 周前

响应式 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坐标检索到的位置信息,例如纬度和经度
locatedAtDate上次地理定位调用的时间
errorstring地理定位 API 失败时的错误消息。
resumefunction恢复更新地理定位的控制函数
pausefunction暂停更新地理定位的控制函数

配置

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>

源代码

SourceDemo文档

贡献者

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

更新日志

v12.0.0-beta.1 于 2024/11/21
0a9ed - feat!: 删除 Vue 2 支持,优化 bundles 并清理 (#4349)

根据 MIT 许可证发布。