useGeolocation
useGeolocation 是一个获取并跟踪用户地理位置的 React Hook。它使用浏览器的 Geolocation API,同时支持一次性位置获取和持续的定位跟踪。
接口
ts
function useGeolocation(options?: GeolocationOptions): Object;参数
- optionsGeolocationOptions
地理位置选项配置
- options.mountBehaviorGeolocationMountBehaviorType
挂载时 Hook 的行为:
- 若未提供,则不自动获取位置
-get:组件挂载时自动获取一次位置
-watch:组件挂载时自动开始跟踪位置变化 - options.enableHighAccuracyboolean · false
若为 true,则提供更精确的位置信息(会增加电池消耗)
- options.maximumAgenumber · 0
可返回的缓存位置可接受的最大年限(毫秒)
- options.timeoutnumber · Infinity
位置请求允许的最大时间(毫秒)
- options.mountBehaviorGeolocationMountBehaviorType
返回值
- Object
包含位置数据和相关函数的对象
- loadingboolean
是否正在获取位置数据。
- errorCustomGeoLocationError|null
出错时的错误对象,否则为 null。Hook 使用标准 Geolocation API 错误代码(
1-3),并新增自定义代码(0)
:0- 环境不支持 Geolocation
:1- 用户拒绝授予地理位置访问权限
:2- 位置不可用
:3- 超时 - 地理位置请求耗时过长。 - dataGeolocationData|null
位置数据对象或 null
: latitudenumber- 以十进制度表示的纬度
: longitudenumber- 以十进制度表示的经度
: accuracynumber- 以米表示的位置精度
: altitudenumber|null- 以米表示的、相对于 WGS84 椭球体的海拔
: altitudeAccuracynumber|null- 以米表示的海拔精度
: headingnumber|null- 从正北顺时针计算的航向角(度)
: speednumber|null- 以米每秒表示的速度
: timestampnumber- 位置被获取的时间。 - getCurrentPositionFunction
一次性获取当前位置的函数。
- startTrackingFunction
开始跟踪位置变化的函数。
- stopTrackingFunction
停止跟踪位置的函数。
- isTrackingboolean
位置跟踪当前是否处于活跃状态。
- loadingboolean
示例
tsx
// Basic usage
const { loading, error, data, getCurrentPosition } = useGeolocation();
// Automatically fetch location when component mounts
const { loading, error, data } = useGeolocation({ mountBehavior: 'get' });
// Location tracking
const { loading, error, data, startTracking, stopTracking, isTracking } =
useGeolocation();
const handleStartTracking = () => {
startTracking();
};
const handleStopTracking = () => {
stopTracking();
};