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

295
Vistas
How to remove Leaflet Marker in L.easyButton?

I'm using an L.easyButton to add and remove a leaflet marker based on the current location. This is my code:

var marker;

L.easyButton({
    states: [{
        stateName: 'on',
        title: 'Add Marker',
        onClick: function(btn, map) {
            map.locate({ setView: true, maxZoom: 16 });

            function onLocationFound(e) {
                marker = L.marker(e.latlng).addTo(map);
            }
            map.on('locationfound', onLocationFound);
            btn.state('off');
        }
    }, {
        stateName: 'off',
        title: 'Remove Marker',
        onClick: function(btn, map) {
            if (map.hasLayer(marker)) {
               map.removeLayer(marker); 
               //map.removeControl(marker);        
           }
            btn.state('on');
        }
    }]
}).addTo(map);

The code works well when added and removed the marker for the first time. But when I clicked the button again, the marker can added, but it failed to be removed.

FYI, the button state can be changed successfully, just the removal function is not working.

I have tried these both code lines in the remove function, but it didn't work.

map.removeLayer(marker); 
map.removeControl(marker);

How should I improve the code? Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

What happens is that the next times you request a geolocation and create a corresponding Marker, you actually stack up your event listener, hence create several Markers at the same position.

Therefore when trying to remove it later on, the very last one is correctly removed, but there are still some Markers at that position, leading to the impression that nothing happened.

A simple solution consists in removing the event listener after it has been used, typically with .once() method (instead of .on()):

map.once('locationfound', onLocationFound);
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