跳至主要内容

useGeolocation

跟蹤地理位置的 React Hook

如果用户愿意,它允许用户向網路应用程序提供他们的位置。 出于隐私原因,报告位置信息需要用户许可

Usage

即時編輯器

function Demo() {
  const { coordinates, locatedAt, error } = useGeolocation();

  return (
    <div>
      <pre lang="json">
        {JSON.stringify(
          {
            coordinates: {
              accuracy: coordinates.accuracy,
              latitude: coordinates.latitude,
              longitude: coordinates.longitude,
              altitude: coordinates.altitude,
              altitudeAccuracy: coordinates.altitudeAccuracy,
              heading: coordinates.heading,
              speed: coordinates.speed,
            },
            locatedAt,
            error: error ? error.message : error,
          },
          null,
          2,
        )}
      </pre>
    </div>
  );
};

結果
Loading...

API

useGeoLocation

Returns

{ readonly coordinates: GeolocationCoordinates; readonly locatedAt: number | null; readonly error: GeolocationPositionError | null; readonly isSupported: boolean; }: 包含以下元素的對象:

  • 坐標。
  • 獲取坐標的時間戳。
  • 錯誤。
  • 瀏覽器是否支援 geolocation

Arguments

參數名描述類型預設值
options可选 PositionOptions 参数Partial<PositionOptions> | undefined-