12

I would like to show icons if the user zooms to level 7 or more and hide the markers when zoom level is 6 or lower. I've tried using the 'zoomend' property in my function like so:

var shelter1 = L.marker([55.1, 11.6], {icon: shelterIcon}).addTo(map);

    map.on('zoomend', function() {
        var currentZoom = map.getZoom();
        if(currentZoom >= 7) {
          shelter1.bindPopup("Shelter");
        }
        else {
          shelter1.hide();
        }
    });

I know that hide() is not valid. But I need something similar. Couldn't find anything in the Leaflet documentation.

1
  • To remove popup: shelter1.unbindPopup();
    – TomazicM
    Oct 15, 2017 at 9:56

1 Answer 1

22

All right. I came up with a solution using a layer:

var shelter1 = L.marker([55.08, 11.62], {icon: shelterIcon});

var shelterMarkers = new L.FeatureGroup();

shelterMarkers.addLayer(shelter1);

map.on('zoomend', function() {
    if (map.getZoom() <7){
            map.removeLayer(shelterMarkers);
    }
    else {
            map.addLayer(shelterMarkers);
        }
});
1
  • This should be accepted as the answer. Thank you very much Saud. Nov 21, 2020 at 0:56

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