UNPKG

1.12 kBJavaScriptView Raw
1import { useCallback, useState } from 'react';
2export default function useGeolocation({ onSuccess, onError } = {}) {
3 const provider = typeof navigator !== 'undefined' && navigator.geolocation;
4 const [position, setPosition] = useState();
5 const success = useCallback(position => {
6 setPosition(position);
7 onSuccess && onSuccess(position);
8 }, [onSuccess, setPosition]);
9 const error = useCallback(err => {
10 setPosition(undefined);
11 onError && onError(err);
12 }, [onError, setPosition]);
13 const getPosition = useCallback(config => {
14 if (!provider)
15 return;
16 provider.getCurrentPosition(success, error, config);
17 }, [provider, error, success]);
18 const watchPosition = useCallback(config => {
19 if (!provider)
20 return;
21 const id = provider.watchPosition(success, error, config);
22 return () => provider.clearWatch(id);
23 }, [provider, error, success]);
24 return {
25 isAvailable: !!provider,
26 position,
27 getPosition,
28 watchPosition
29 };
30}
31//# sourceMappingURL=useGeolocation.js.map
\No newline at end of file