I have a react app which shows the users location on map using react-leaflet. I used navigator.geolocation to get the position and sets it to the userData state when user allows access. Sometimes it is showing it on map but sometimes it is returning undefined.
redux-action :
export const getUserData = () => {
return async (dispatch) => {
if(navigator.geolocation) {
navigator.geolocation.watchPosition((position) => {
dispatch({
type: FETCH_USER_DATA,
payload: position.coords
})
})
} else {
alert('Unable to get location')
}
}
}
reducer :
export const rootReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_IP_LOCATION:
return {
...state,
ipLocation: action.payload,
isLoading: false,
}
case FETCH_USER_DATA:
return {
...state,
userData: action.payload,
isLoading: false,
}
}
}
Component which renders map :
import React from 'react';
import '../styles/MapComponent.css';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import { useEffect } from 'react';
import { getUserData } from '../redux/action/';
import { useDispatch, useSelector } from 'react-redux'
const MapComponent = () => {
const dispatch = useDispatch()
const isLoading = useSelector((state) => state.isLoading)
const coord = useSelector((state) => state.userData)
useEffect(() => {
dispatch(getUserData())
}, [])
return (
<MapContainer center={[coord.latitude, coord.longitude]} zoom={12}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[coord.latitude, coord.longitude]}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
)
}
export default MapComponent