46 lines
1.5 KiB
JavaScript
46 lines
1.5 KiB
JavaScript
import { __assign } from "tslib";
|
|
import { useEffect, useState } from 'react';
|
|
var useGeolocation = function (options) {
|
|
var _a = useState({
|
|
loading: true,
|
|
accuracy: null,
|
|
altitude: null,
|
|
altitudeAccuracy: null,
|
|
heading: null,
|
|
latitude: null,
|
|
longitude: null,
|
|
speed: null,
|
|
timestamp: Date.now(),
|
|
}), state = _a[0], setState = _a[1];
|
|
var mounted = true;
|
|
var watchId;
|
|
var onEvent = function (event) {
|
|
if (mounted) {
|
|
setState({
|
|
loading: false,
|
|
accuracy: event.coords.accuracy,
|
|
altitude: event.coords.altitude,
|
|
altitudeAccuracy: event.coords.altitudeAccuracy,
|
|
heading: event.coords.heading,
|
|
latitude: event.coords.latitude,
|
|
longitude: event.coords.longitude,
|
|
speed: event.coords.speed,
|
|
timestamp: event.timestamp,
|
|
});
|
|
}
|
|
};
|
|
var onEventError = function (error) {
|
|
return mounted && setState(function (oldState) { return (__assign(__assign({}, oldState), { loading: false, error: error })); });
|
|
};
|
|
useEffect(function () {
|
|
navigator.geolocation.getCurrentPosition(onEvent, onEventError, options);
|
|
watchId = navigator.geolocation.watchPosition(onEvent, onEventError, options);
|
|
return function () {
|
|
mounted = false;
|
|
navigator.geolocation.clearWatch(watchId);
|
|
};
|
|
}, []);
|
|
return state;
|
|
};
|
|
export default useGeolocation;
|