跳到主要内容

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; }: 包含以下元素的元组:

  • 坐标。
  • 获取坐标的时间戳。
  • 错误。

Arguments

参数名描述类型默认值
options可选 PositionOptions 参数Partial<PositionOptions> | undefined-