5

I have a simple Marker added to map like this:
var x = L.marker([50.5, 30.5]); x.addTo(map);

Now how can I hide/remove x? I searched the API docs for a Marker.remove() method, but couldn't find any.

Even more odd - Google is failing me. All results I can get is how to remove the whole layer with all markers, but not only one.

Am I getting something wrong here about markers? Is there a way to remove only one?

3 Answers 3

8

Yes, it might sound confusing but internally markers are treated like layers. You have to use removeLayer, it will still only remove a single marker:

var x = L.marker([51.5, -0.09]).addTo(map);
var y = L.marker([51.45, -0.09]).addTo(map);
map.removeLayer(x);
0

First, adding a lot of markers:

for (var i=0; i < schools.length;i++){
    var marker = L.marker([schools[i].latLng.lat, schools[i].latLng.lng], {
          icon: L.mapbox.marker.icon({
            'marker-color': '#9c89cc'
          })
        })
        .bindPopup('<div class=\"marker-title\"><h2>'+schools[i].uniName+'</h2></div>')
        .addTo(map);
    allMarkers.push(marker);
  }

Then hiding that specific marker (in this case I just hide the first, but you could hide based on any number of variables):

$(allMarkers[0]._icon).hide()
0

Note this answer is outdated. The current behaviour would be x.remove()

https://docs.mapbox.com/mapbox-gl-js/api/markers/#marker#remove

1
  • 1
    There is Mapbox and Mapbox ;) e.g "Mapbox.js" github.com/mapbox/mapbox.js (Leaflet based) and Mapbox GL JS docs.mapbox.com/mapbox-gl-js Historic answer fine if you consider the 1st, not as you mentioned if you consider the 2nd. Updated the main question title as the link in the original question was for Mapbox.js not Mapbox GL JS
    – ThomasG77
    Apr 1, 2021 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.