Created
November 7, 2019 22:02
-
-
Save rajinwonderland/48e1cdb3ffc54f23bb07b7cae5abc9d7 to your computer and use it in GitHub Desktop.
react-hooks-collection
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
// originally from 'react-use' library! | |
import { useEffect, useState } from 'react'; | |
export interface GeoLocationSensorState { | |
loading: boolean; | |
accuracy: number | null; | |
altitude: number | null; | |
altitudeAccuracy: number | null; | |
heading: number | null; | |
latitude: number | null; | |
longitude: number | null; | |
speed: number | null; | |
timestamp: number | null; | |
error?: Error | PositionError; | |
} | |
const useGeolocation = (options?: PositionOptions): GeoLocationSensorState => { | |
const [state, setState] = useState<GeoLocationSensorState>({ | |
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: any) => { | |
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: PositionError) => | |
mounted && setState(oldState => ({ ...oldState, loading: false, error })); | |
useEffect(() => { | |
navigator.geolocation.getCurrentPosition(onEvent, onEventError, options); | |
watchId = navigator.geolocation.watchPosition(onEvent, onEventError, options); | |
return () => { | |
mounted = false; | |
navigator.geolocation.clearWatch(watchId); | |
}; | |
}, []); | |
return state; | |
}; | |
export default useGeolocation; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment