Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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>   
); }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!