Skip to content

Instantly share code, notes, and snippets.

@exaucae
Created November 9, 2021 22:53
Show Gist options
  • Save exaucae/d95fd124a8f07aeee61d6b72db562bd0 to your computer and use it in GitHub Desktop.
Save exaucae/d95fd124a8f07aeee61d6b72db562bd0 to your computer and use it in GitHub Desktop.
React hook that retrieves current user position
import React, {useState} from 'react'
const useLocation = () => {
const initialState = {
latitude: '',
longitude: '',
error: '',
accuracy: '',
timestamp: ''
}
const [userCoordinates, setUserCoordinates] = useState(initialState);
function onSuccess(position) {
setUserCoordinates((prevState) => ({
...prevState,
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
timestamp: position.timestamp,
}))
}
function onError() {
setUserCoordinates((prevState) => ({
...prevState,
error: 'Geolocation is not supported by your browser',
}))
}
if (!navigator.geolocation) {
setUserCoordinates(() => ({
...initialState,
error: 'Geolocation is not supported by your browser',
}))
} else {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
return (
{
latitude: userCoordinates.latitude,
longitude: userCoordinates.longitude,
timestamp: userCoordinates.timestamp,
accuracy: userCoordinates.accuracy,
error: userCoordinates.error,
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment