Skip to content

useGeolocation

类别
导出体积
526 B
上次更改
2 minutes ago

提供响应式的 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()
状态类型描述
coordsCoordinates获取的位置信息,如纬度和经度
locatedAtDate最后一次地理定位的时间
errorstring如果地理定位 API 失败,则显示错误消息。
resumefunction控制函数,用于恢复更新地理定位。
pausefunction控制函数,用于暂停更新地理定位。

配置

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

组件使用

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

类型声明

typescript
export interface UseGeolocationOptions
  extends Partial<PositionOptions>,
    ConfigurableNavigator {
  immediate?: boolean
}
/**
 * 响应式 Geolocation API.
 *
 * @see https://vueuse.org/useGeolocation
 * @param options
 */
export declare function useGeolocation(options?: UseGeolocationOptions): {
  isSupported: ComputedRef<boolean>
  coords: Ref<
    Omit<GeolocationCoordinates, "toJSON">,
    Omit<GeolocationCoordinates, "toJSON">
  >
  locatedAt: Ref<number | null, number | null>
  error: ShallowRef<GeolocationPositionError | null>
  resume: () => void
  pause: () => void
}
export type UseGeolocationReturn = ReturnType<typeof useGeolocation>

源码

源码演示文档

贡献者

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

更新日志

v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.7.0 on 12/16/2022
161fd - fix: Implement immediate option (#2472)
v9.5.0 on 11/9/2022
2c4fd - feat: pause and resume controls (#2376)