reactuals
Version:
A useful package providing a collection of 50+ React hooks and utilities to simplify React development.
37 lines (36 loc) • 1.13 kB
JavaScript
import { useState, useEffect } from "react";
export function useGeoLocation(options = {}) {
const [location, setLocation] = useState({
latitude: null,
longitude: null,
error: null,
});
useEffect(() => {
if (!navigator.geolocation) {
setLocation({
latitude: null,
longitude: null,
error: new GeolocationPositionError(),
});
return;
}
const success = (position) => {
setLocation({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
};
const error = (err) => {
setLocation({ latitude: null, longitude: null, error: err });
};
const watchId = navigator.geolocation.watchPosition(success, error, {
enableHighAccuracy: false,
timeout: 10000,
maximumAge: 60000,
...options,
});
return () => navigator.geolocation.clearWatch(watchId);
}, [options]);
return location;
}