Diana Sk
Diana Sk

Reputation: 105

React - Leaflet removing marker

I am trying to add and remove markers in my map, but i have a problem when i try to delete them. The user clicks on the map and puts as many markers as he wants. When he clicks on the popup of a specific marker he can delete it. If for example the user puts 3 markers and wants to delete the second one, when he does so , the second AND THIRD marker disappear from the map.. I store the coordinates in use state hook and although i update properly the array when i delete the marker, the markers do not seem to re-render properly. Do you have any idea what could be wrong?

Thank you very much :)

Here is the AddMarker Component

function AddMarker() {

const [coord, setPosition] = useState([]);

const map = useMapEvents({
    click: (e) => {   
        setPosition([...coord,e.latlng])
        const mark = e
     },   
})

useEffect(() => {
  console.log( coord);
}, [coord]);


const removeMarker = (index, map) => {
  map.eachLayer((layer) => {
    if (layer.options && layer.options.pane === "markerPane") {
      if (layer.options.uniceid === index) {
        console.log(layer.options.uniceid)
        console.log(index)
        map.removeLayer(layer);
        var array = [...coord];
        array.splice(index, 1);
        setPosition(array)

        console.log(array)
        
        //coord.splice(index,1);
        //setPosition(coord=> [...coord]);
        //console.log(coord)

      }
    }
  });
}

return (
  
    <div>
    {coord.map((pos, idx) =>
        <Marker key={`marker-${idx}`} uniceid={idx} position={pos} icon ={blue} draggable={true} eventHandlers={{
            click: (e) => {console.log(e.latlng)},}}>
        <Popup>
            <PopupForm data ={pos} id={idx} formData={() => removeMarker(idx, map)}></PopupForm>
        </Popup>
      </Marker>

    )}
    </div>   
); }

Upvotes: 0

Views: 4011

Answers (1)

kboul
kboul

Reputation: 14580

You don't need to loop over each map layer as you do. You just need to filter the clicked marker' coords not to be included anymore to your state variable and that's it!

Here is a simplified example with a normal button inside the popup

const removeMarker = (pos) => {
        setPosition((prevCoord) =>
          prevCoord.filter(
(prevCoord) => prevCoord.filter((coord) => JSON.stringify(coord) !== JSON.stringify(pos))
            // or (coord) => coord.lat !== pos.lat && coord.lng !== pos.lng 
          )
        );
};
...
return (
          <div>
              {coord.map((pos, idx) => (
                <Marker
                  key={`marker-${idx}`}
                  position={pos}
                  draggable={true}
                  eventHandlers={{
                    click: (e) => {
                      console.log(e.latlng);
                    }
                  }}
                >
                  <Popup>
                    <button onClick={() => removeMarker(pos)}>Remove marker</button>
                  </Popup>
                </Marker>
              ))}
          </div>
 );

Demo

Upvotes: 1

Related Questions