I\'m pretty new to the Leaflet library, and to JavaScript in general, and I\'m stuck trying to figure out how to show/hide a leaflet Label based on the zoom level (and the marke
Since none of the previously posted solutions worked for me, I post here the code that did work, particularly for maps where not every layer object on the map is assumed to be a marker object. Assuming the created L.Map
object is stored in the map
variable, put this after your map initialization code:
var show_label_zoom = 20; // zoom level threshold for showing/hiding labels
var labels_visible = true;
function show_hide_labels() {
var cur_zoom = map.getZoom();
if(labels_visible && cur_zoom < show_label_zoom) {
labels_visible = false;
map.eachLayer(layer => layer.hideLabel && layer.hideLabel());
}
else if(!labels_visible && cur_zoom >= show_label_zoom) {
labels_visible = true;
map.eachLayer(layer => layer.showLabel && layer.showLabel());
}
}
map.on('zoomend', show_hide_labels);
show_hide_labels();