Leaflet: How to control opacity of Layer Groups?

2019-09-11 15:29发布

问题:

Does some expert know how to change the opacity of each tilemap of a Layer Group by using a HTML-slider input?

For example: I've got several tilemaps, which could be switched by using Lealet's Layercontrol button, like here: Leaflet Layer Groups. When using the opacity-slider I want to dim each tilemap, not just one being actually active. For example: I'm dimming map1 to 0.5 Then switching to map2, its opacity should already also be 0.5. And when changing the opacity of map2 to 0.8 with the slider and switching back to map1, map1 should already have opacity 0.8 again (not the former adjusted value of 0.5)

I know how to implement the slider control and how to change the opacity of a single tilemap by using the command

nameOfMaplayer.setOpacity(opacityValue);

But I don't have an idea how to reference using Leaflet's methods to the Pane/Grid Layer/array of all tilemaps to change the map's pane opacity instead of the opacity of each indivdual tilemaps simultaniously.

回答1:

I think in the end I found a satisfying answer myself:

If we want to change the opacity of the tilePane (= basemap-layers AND overlaymap-layers):

map.getPane('tilePane').style.opacity = 0.5;

But this has the disadvantage that also the Overlay-tilemaps get dimmed which I wanted to avoid.

My prefered method is to change just the opacity of the active basemap-layer. Since Leaflet doesn't support getting the active basemap Layer, you'll have to use the "Activelayers"-Plugin and use its methods:

ctrLayer = L.control.activeLayers(baseMaps, overlayMaps, {position: 'topright'}).addTo(map);
.....
tilemapLayer = ctrLayer.getActiveBaseLayer().layer;
tilemapLayer.setOpacity(actualOpacityValue);

Each time you change the basemap, you have to run the later 2 commands to change the new basemap's oppacity to the actual used opacity value.