Skip to content

Instantly share code, notes, and snippets.

@GalindoSVQ
Created January 11, 2024 21:22
Show Gist options
  • Save GalindoSVQ/a294f219b4fee0a3a6f77e7c770d9538 to your computer and use it in GitHub Desktop.
Save GalindoSVQ/a294f219b4fee0a3a6f77e7c770d9538 to your computer and use it in GitHub Desktop.
import * as React from "react";
export function useGeolocation(options = {}) {
const [state, setState] = React.useState({
loading: true,
accuracy: null,
altitude: null,
altitudeAccuracy: null,
heading: null,
latitude: null,
longitude: null,
speed: null,
timestamp: null,
error: null,
});
const optionsRef = React.useRef(options);
React.useEffect(() => {
const onEvent = ({ coords, timestamp }) => {
setState({
loading: false,
timestamp,
latitude: coords.latitude,
longitude: coords.longitude,
altitude: coords.altitude,
accuracy: coords.accuracy,
altitudeAccuracy: coords.altitudeAccuracy,
heading: coords.heading,
speed: coords.speed,
error: null,
});
};
const onEventError = (error) => {
setState((s) => ({
...s,
loading: false,
error,
}));
};
navigator.geolocation.getCurrentPosition(
onEvent,
onEventError,
optionsRef.current
);
const watchId = navigator.geolocation.watchPosition(
onEvent,
onEventError,
optionsRef.current
);
return () => navigator.geolocation.clearWatch(watchId);
}, [options]);
return state;
}
@GalindoSVQ
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment