Skip to content

Instantly share code, notes, and snippets.

@lsbyerley
Created March 6, 2021 14:33
Show Gist options
  • Save lsbyerley/7d0c01cd7f2a892f3f8e7dcc80993760 to your computer and use it in GitHub Desktop.
Save lsbyerley/7d0c01cd7f2a892f3f8e7dcc80993760 to your computer and use it in GitHub Desktop.
useLocation React Hook
import { useState, useEffect } from "react";
const useCurrentLocation = (options = {}) => {
// store location in state
const [location, setLocation] = useState();
// store error message in state
const [error, setError] = useState();
// Success handler for geolocation's `getCurrentPosition` method
const handleSuccess = (pos) => {
const { latitude, longitude } = pos.coords;
setLocation({
latitude,
longitude,
});
};
// Error handler for geolocation's `getCurrentPosition` method
const handleError = (error) => {
setError(error.message);
};
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;
}
// Call Geolocation API
geolocation.getCurrentPosition(handleSuccess, handleError, options);
}, [options]);
return { location, error };
};
export default useCurrentLocation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment