Skip to content

Instantly share code, notes, and snippets.

@jqn
Created December 3, 2020 13:44
Show Gist options
  • Save jqn/cce1a85596dc9765c57851cfc8f79b60 to your computer and use it in GitHub Desktop.
Save jqn/cce1a85596dc9765c57851cfc8f79b60 to your computer and use it in GitHub Desktop.
React geolocation example
import React from 'react'
import ReactDOM from 'react-dom'
function geoPositionReducer(state, action) {
switch (action.type) {
case 'error': {
return {
...state,
status: 'rejected',
error: action.error,
}
}
case 'success': {
return {
...state,
status: 'resolved',
position: action.position,
}
}
case 'start': {
return {
...state,
status: 'pending',
}
}
default: {
throw new Error(`Unhandled action type: ${action.type}`)
}
}
}
function useGeoPosition() {
const [state, dispatch] = React.useReducer(geoPositionReducer, {
status: 'idle',
position: null,
error: null,
})
React.useEffect(() => {
if (!navigator.geolocation) {
dispatch({
type: 'error',
error: new Error('Geolocation is not supported'),
})
return
}
dispatch({type: 'start'})
const geoWatch = navigator.geolocation.watchPosition(
position => dispatch({type: 'success', position}),
error => dispatch({type: 'error', error}),
)
return () => navigator.geolocation.clearWatch(geoWatch)
}, [])
return state
}
function YourPosition() {
const {status, position, error} = useGeoPosition()
if (status === 'idle' || status === 'pending') {
return <div>Loading your position...</div>
}
if (status === 'resolved') {
return (
<div>
Lat: {position.coords.latitude}, Long: {position.coords.longitude}
</div>
)
}
if (status === 'rejected') {
return (
<div>
<div>Oh no, there was a problem getting your position:</div>
<pre>{error.message}</pre>
</div>
)
}
}
ReactDOM.render(<YourPosition />, document.getElementById('root'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment