Skip to content

Instantly share code, notes, and snippets.

@freddi301
Last active February 7, 2024 10:15
Show Gist options
  • Save freddi301/e8a6f025870427027d7130cf2fbd7fba to your computer and use it in GitHub Desktop.
Save freddi301/e8a6f025870427027d7130cf2fbd7fba to your computer and use it in GitHub Desktop.
React hook for geolocation
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