Last active
February 7, 2024 10:15
-
-
Save freddi301/e8a6f025870427027d7130cf2fbd7fba to your computer and use it in GitHub Desktop.
React hook for geolocation
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 React from "react"; | |
export function useGeolocation({ | |
isEnabled, | |
positionOptions: { enableHighAccuracy, maximumAge, timeout }, | |
startTransition, | |
}: { | |
isEnabled: boolean; | |
positionOptions: PositionOptions; | |
startTransition?(update: () => void): void; | |
}) { | |
const [state, setState] = React.useState< | |
| { position: GeolocationPosition; error: undefined } | |
| { position: undefined; error: GeolocationPositionError } | |
| { position: undefined; error: undefined } | |
>({ position: undefined, error: undefined }); | |
React.useEffect(() => { | |
if (isEnabled) { | |
const watcher = navigator.geolocation.watchPosition( | |
(position) => { | |
const update = () => setState({ position, error: undefined }); | |
if (startTransition) startTransition(update); | |
else update(); | |
}, | |
(error) => { | |
const update = () => setState({ position: undefined, error }); | |
if (startTransition) startTransition(update); | |
else update(); | |
}, | |
{ enableHighAccuracy, maximumAge, timeout } | |
); | |
return () => { | |
navigator.geolocation?.clearWatch(watcher); | |
}; | |
} | |
}, [enableHighAccuracy, isEnabled, maximumAge, startTransition, timeout]); | |
if (isEnabled) return state; | |
else return { position: undefined, error: undefined }; | |
} | |
export function getGeolocation(positionOptions: PositionOptions) { | |
return new Promise<GeolocationPosition>((resolve, reject) => { | |
navigator.geolocation.getCurrentPosition(resolve, reject, positionOptions); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment