I am working with React Leaflet right now and I need to get the coordinates of the position I clicked on the map. when I googled it I could only find latlng as a solution, but that is not working. any ideas? TIA
Asked
Active
Viewed 1,590 times
1 Answers
0
I found a solution, attached the code that could help you in your problem.
import React, {useState} from "react";
import {Map, Marker, TileLayer} from "react-leaflet";
const style = {
height: '400px',
width: '100%'
};
export const Ubication = () => {
const [position] = useState([-0.22021954674229854, -78.5127639770508]);//position intitial of map
const [marker, setMarker] = useState({lat: 0, lng: 0});
function changeUbication(e) {
let {lat, lng} = e.latlng;
console.info("Lat:", lat);
console.info("Lng: ",lng);
setMarker(e.latlng);
}
return (
<div id="map">
<Map center={position}
zoom={13}
onClick={changeUbication}
style={style}>
<TileLayer
url='https://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'/>
{(marker.lat !== 0 && marker.lng !== 0) &&
<Marker position={[marker.lat, marker.lng]}>
</Marker>}
</Map>
</div>)
}

Jc228
- 1