Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda