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

291
Views
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 answers
Answer question

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 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!