Created
March 7, 2021 15:35
-
-
Save lsbyerley/e5c708918f75e27cbd6f1edecf1c0e48 to your computer and use it in GitHub Desktop.
useWatchLocation Location API Hook
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
import { useState, useEffect, useRef } from "react"; | |
const useWatchLocation = (options = {}) => { | |
// store location in state | |
const [location, setLocation] = useState(); | |
// store error message in state | |
const [error, setError] = useState(); | |
// save the returned id from the geolocation's `watchPosition` to be able to cancel the watch instance | |
const locationWatchId = useRef(null); | |
// Success handler for geolocation's `watchPosition` method | |
const handleSuccess = (pos) => { | |
const { latitude, longitude } = pos.coords; | |
setLocation({ | |
latitude, | |
longitude, | |
}); | |
}; | |
// Error handler for geolocation's `watchPosition` method | |
const handleError = (error) => { | |
setError(error.message); | |
}; | |
// Clears the watch instance based on the saved watch id | |
const cancelLocationWatch = () => { | |
const { geolocation } = navigator; | |
if (locationWatchId.current && geolocation) { | |
geolocation.clearWatch(locationWatchId.current); | |
} | |
}; | |
useEffect(() => { | |
const { geolocation } = navigator; | |
// If the geolocation is not defined in the used browser we handle it as an error | |
if (!geolocation) { | |
setError("Geolocation is not supported."); | |
return; | |
} | |
// Start to watch the location with the Geolocation API | |
locationWatchId.current = geolocation.watchPosition(handleSuccess, handleError, options); | |
// Clear the location watch instance when React unmounts the used component | |
return cancelLocationWatch; | |
}, [options]); | |
return { location, cancelLocationWatch, error }; | |
}; | |
export default useWatchLocation; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment