Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda