Reputation: 2692
Is there any performant solution for getting latitude and longitude in react-leaflet when moving the mouse on the map and showing it as text below the mapContainer? Is there any clear documentation for react-leaflet events?
Upvotes: 1
Views: 2048
Reputation: 14570
After receiving the map instance, you can listen to map's mousemove
event when the component mounts. You can store then the lat
andlng
derived from the event and display them under the map accordingly:
const [coords, setCoords] = useState({});
useEffect(() => {
if (!map) return;
map.addEventListener("mousemove", (e) => {
setCoords({ lat: e.latlng.lat, lng: e.latlng.lng });
});
}, [map]);
and then under the map
{lat && (
<div>
<b>latitude</b>: {lat?.toFixed(4)} <br />
<b>longitude</b>: {lng?.toFixed(4)}
</div>
)}
Upvotes: 2