Skip to content Skip to sidebar Skip to footer

Labels Only Appear If Zoom Leaflet

I'm making a map in Leaflet and I have up to two labels per marker: var redIcon = new L.Icon({ iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/im

Solution 1:

Instead of adding the label to the map, add it to a L.featureGroup:

var fg = L.featureGroup().addTo(map);
...
functioncreateLabel(layer, text, count){
   ...
   var label = L.marker(layer.getLatLng(),{icon: icon}).addTo(fg);
   ...
} 

And then remove / add the group while zooming:

functionshow_hide_labels() {
    var cur_zoom = mymap.getZoom();
    if(cur_zoom < show_label_zoom && mymap.hasLayer(fg)) {       
        mymap.removeLayer(fg);            
    } elseif(!mymap.hasLayer(fg) && cur_zoom >= show_label_zoom) {            
        mymap.addLayer(fg);                 
    }
}
mymap.on('zoomend', show_hide_labels);
show_hide_labels();

Post a Comment for "Labels Only Appear If Zoom Leaflet"