Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Last active October 9, 2023 19:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save whoisryosuke/e3ad7f43924dec60a12e247efe743e70 to your computer and use it in GitHub Desktop.
Save whoisryosuke/e3ad7f43924dec60a12e247efe743e70 to your computer and use it in GitHub Desktop.
React Hooks - Geolocation use native browser API

useGeolocation

React sensor hook that tracks user's geographic location.

Hook

const useGeolocation = () => {
  const [state, setState] = useState({
    accuracy: null,
    altitude: null,
    altitudeAccuracy: null,
    heading: null,
    latitude: null,
    longitude: null,
    speed: null,
    timestamp: Date.now()
  });
  let mounted = true;
  let watchId;

  const onEvent = event => {
    if (mounted) {
      setState({
        accuracy: event.coords.accuracy,
        altitude: event.coords.altitude,
        altitudeAccuracy: event.coords.altitudeAccuracy,
        heading: event.coords.heading,
        latitude: event.coords.latitude,
        longitude: event.coords.longitude,
        speed: event.coords.speed,
        timestamp: event.timestamp
      });
    }
  };

  useEffect(
    () => {
      navigator.geolocation.getCurrentPosition(onEvent);
      watchId = navigator.geolocation.watchPosition(onEvent);

      return () => {
        mounted = false;
        navigator.geolocation.clearWatch(watchId);
      };
    },
    [0]
  );

  return state;
};

Usage

import {useGeolocation} from 'react-use';

const Demo = () => {
  const state = useGeolocation();

  return (
    <pre>
      {JSON.stringify(state, null, 2)}
    </pre>
  );
};

Response

{
  "accuracy": null,
  "altitude": null,
  "altitudeAccuracy": null,
  "heading": null,
  "latitude": null,
  "longitude": null,
  "speed": null,
  "timestamp": 1541445551039
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment