2

I would like to control the opacity of a wms layer (using L.tileLayer.wms) in Leaflet using an opacity slider.

In L.tileLayer.wms I can control the opacity by setting the opacity:value.

This is my piece of code; The wms layer

var wmsLayer_2 = L.tileLayer.wms('https://wms.cartografia.agenziaentrate.gov.it/inspire/wms/ows01.php', {
  layers: ['CP.CadastralParcel'],
  crs: crs_6706,
    format: 'image/png',
  maxZoom: 21,
  transparent: true,
}).addTo(map);

The slider implemented in the leaflet control

function updateOpacity(value) {
        wmsLayer_2.setParams({opacity:value});
        };

var control = L.control.layers(baseMaps,
    {'Opacity_layer <br><input id="range" type="range" min="0" max="1" step="0.1" value="1" class="slider" onchange="updateOpacity(this.value)">':wmsLayer_2},{collapsed: false}).addTo(map);

However I can't manage the opacity.

Here a complete example

2 Answers 2

2

You're confusing the Leaflet opacity option with a opacity WMS parameter.

When instantiating a L.TileLayer.WMS, any options that are not known to Leaflet are treated as WMS parameters, as explained in the documentation:

If any custom options not documented here are used, they will be sent to the WMS server as extra parameters in each request URL. This can be useful for non-standard vendor WMS parameters.

This can be confusing, since the both options and WMS parameters are mixed together when instantiating.

However, the setParams() method works only on WMS parameters, not on options. So when instantiating, opacity is treated as a Leaflet option, but when passed to setParams, it's treated as a WMS parameter (and, in fact, in your example there's a &opacity= parameter appended to the URL of any WMS tile requests made by the browser).

tl;dr: use the setOpacity() method instead.

2

In your updateOpacity function you should use layer's setOpacity method:

function updateOpacity(value) {
  wmsLayer_2.setOpacity(value);
};
1
  • 1
    Answer from @IvanSanchez should be accepted since it's more complete with explanation. My answer was published about 5 minutes before his, otherwise I wouldn't publish it at all.
    – TomazicM
    Commented Sep 23, 2020 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.