Search code examples
javascriptreactjsleafletmapsreact-leaflet

How to get coordinates of current mouse click in leaflet react js


I'm trying to get coordinates of where the mouse clicks on the map but .locate() only returns the center coordinates of the map. Is there a way? ps. I am not using class based react. Thanks

 <MapContainer
          center={[ 33.8735578, 35.86379]}
        zoom={9}
        scrollWheelZoom={true}
  
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
</MapContainer>

Solution

  • you can get coordinates of mouse click by useMapEvents hook.

    try this one.

    const MapEvents = () => {
        useMapEvents({
          click(e) {
            // setState your coords here
            // coords exist in "e.latlng.lat" and "e.latlng.lng"
            console.log(e.latlng.lat);
            console.log(e.latlng.lng);
          },
        });
        return false;
    }
    
        return (
           <MapContainer
              center={[ 33.8735578, 35.86379]}
              zoom={9}
              scrollWheelZoom={true}
           >
              <TileLayer
              attribution='&copy; <a 
               href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
               url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              />
                <MapEvents />
        </MapContainer>
        )