Skip to content

Instantly share code, notes, and snippets.

@codemile
Created July 27, 2021 10:54
Show Gist options
  • Save codemile/562cd8880ccfd694b71cde0c6c79addb to your computer and use it in GitHub Desktop.
Save codemile/562cd8880ccfd694b71cde0c6c79addb to your computer and use it in GitHub Desktop.
Hook for watching the users current location as geo coordinates.
import {useEffect, useState} from 'react';
const useGeoLocation = (options?: PositionOptions) => {
const [geo, setGeo] = useState<GeolocationPosition>();
const [err, setError] = useState<GeolocationPositionError>();
useEffect(() => {
const id = navigator.geolocation.watchPosition(
(pos) => {
setGeo(pos);
err && setError(undefined);
},
(err) => setError(err),
options
);
return () => navigator.geolocation.clearWatch(id);
}, [err, options]);
return [geo, err];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment