Created
January 11, 2024 21:22
-
-
Save GalindoSVQ/a294f219b4fee0a3a6f77e7c770d9538 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackblitz.com/edit/stackblitz-starters-xnnwff?file=src%2FApp.tsx