diff options
author | Nick Van Doorn <vandoorn.nick@gmail.com> | 2019-03-29 00:35:56 -0700 |
---|---|---|
committer | Nick Van Doorn <vandoorn.nick@gmail.com> | 2019-03-29 00:35:56 -0700 |
commit | 65220cc8db0d7c63f49627526466d54969958fe1 (patch) | |
tree | e2989cb16576f177e60f75f9a733487adfd868f5 /src/use-geolocation.js | |
parent | 51687fe7a2de2d4ed2800af46f9b6a9ac6c929ee (diff) |
Init commit
Diffstat (limited to 'src/use-geolocation.js')
-rw-r--r-- | src/use-geolocation.js | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/src/use-geolocation.js b/src/use-geolocation.js new file mode 100644 index 0000000..9ab3f99 --- /dev/null +++ b/src/use-geolocation.js @@ -0,0 +1,52 @@ +// lifted from here @ b72c098: +// https://github.com/streamich/react-use/blob/master/src/useGeolocation.ts +import { useState, useEffect } from 'react' + +export const useGeolocation = () => { + const [state, setState] = useState({ + loading: true, + accuracy: null, + altitude: null, + altitudeAccuracy: null, + heading: null, + latitude: null, + longitude: null, + speed: null, + timestamp: Date.now() + }) + let mounted = true + let watchId: any + + const onEvent = event => { + if (mounted) { + setState({ + loading: false, + 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 + }) + } + } + const onEventError = error => + mounted && setState(oldState => ({ ...oldState, loading: false, error })) + + useEffect( + () => { + navigator.geolocation.getCurrentPosition(onEvent, onEventError) + watchId = navigator.geolocation.watchPosition(onEvent, onEventError) + + return () => { + mounted = false + navigator.geolocation.clearWatch(watchId) + } + }, + [0] + ) + + return state +} |