5

This question already has an answer here:

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.

marked as duplicate by Andre Silva, LaughU, csk, JGH, Barbarossa Jan 16 at 15:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • To remove popup: shelter1.unbindPopup(); – TomazicM Oct 15 '17 at 9:56
12

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);
        }
});

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