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

后端 未结 2 1587
夕颜
夕颜 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:45

    Leaflet's layers don't have events fired when zooming the map. The actual map instance does. But binding an eventhandler to each feature would turn into a performance nightmare when you start having more features. You're better off handling the map zoomevent and then fetching all the features in your layer and showing the labels if needed. For example:

    var geoJsonLayer = L.geoJson(featureCollection, {
        onEachFeature: function (feature, layer) {
            layer.bindLabel(feature.geometry.coordinates.toString());
        }
    }).addTo(map);
    
    var visible;
    
    // Attach map zoom handler
    map.on('zoomend', function (e) {
        // Check zoom level
        if (map.getZoom() > 10) {
            // Check if not already shown
            if (!visible) {
                // Loop over layers
                geoJsonLayer.eachLayer(function (layer) {
                    // Show label
                    layer.showLabel();
                });
                // Set visibility flag
                visible = true;
            }
        } else {
            // Check if not already hidden
            if (visible) {
                // Loop over layers
                geoJsonLayer.eachLayer(function (layer) {
                    // Hide label
                    layer.hideLabel();
                });
                // Set visibility flag
                visible = false;
            }
        }
    });
    
    // Fits to layer bounds which automaticly will fire the zoomevent
    map.fitBounds(geoJsonLayer.getBounds());
    

    Here's a working example on Plunker: http://plnkr.co/edit/V8duPDjKlY48MTHOU35F?p=preview

提交回复
热议问题