How do I show a label beyond a certain zoom level in Leaflet?

后端 未结 2 1586
夕颜
夕颜 2021-02-14 11:24

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

2条回答
  •  醉话见心
    2021-02-14 11:59

    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.Mapobject 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();
    

提交回复
热议问题