跳到主要內容

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座標關於檢索到的位置資訊,例如緯度和經度
locatedAt日期上次地理位置呼叫的時間
error字串地理位置 API 失敗時的錯誤訊息。
resume函式用於恢復更新地理位置的控制函式
pause函式用於暫停更新地理位置的控制函式

設定

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.dev.org.tw/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
Anthony Fu
丶遠方
vaakian X
Enric Bisbe Gil
Egor Startsev
Michael J. Roberts
Shinigami
wheat
Alex Kozack
Sanxiaozhizi

更新日誌

v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: 移除 Vue 2 支援,最佳化 bundle 並清理程式碼 (#4349)

以 MIT 授權條款發布。