Leaflet & WMS – Transparent NoData Handling

geoserverjavascriptleaflettransparencywms

I'm trying to create a Leaflet map with an OpenStreetMap as a basemap and a layer from a GeoServer WMS.

I use:

var wmsLayer = L.tileLayer.wms('http://localhost:8080/geoserver/workspace/wms', {
        layers: 'workspace:imgfile.tif',
        transparent: true       
        }).addTo(map);

to include the layer.

Unfortunately the no data values in and around the map are shown as white.

The NoData in the underlying .tif are set to 255. The .tif shows as intended in QGIS.

I included <ColorMapEntry color="#FFFFFF" quantity="255" opacity="0"/> in the geoserver-style (SLD) used. I also tried adding an alpha channel with gdalwarp -dstalpha but it doesn't work.

I have observed that the area outside the extent of the .tif is also white. So maybe the L.tileLayer.wms() is not understood as an overlay but Leaflet is just showing this layer only?

Using the same WMS source in OpenLayers (ol.source.TileWMS()) shows the data correctly (transparent at NoData and outside extent) which indicates further that the data is OK and the issue is to be resolved within leaflet (unlike this related solution).

Links for reference: 1 2 3

Best Answer

Make sure to set the format option of the L.TileLayer.WMS to image/png, as explained in the documentation.

The default is to use .jpg for map image tiles, which is a image format which doesn't handle transparency. Leaflet does not override the format option depending on the value of the transparent option.

e.g.:

var wmsLayer = L.tileLayer.wms('http://localhost:8080/geoserver/workspace/wms', {
    layers: 'workspace:imgfile.tif',
    transparent: true,
    format: 'image/png'
}).addTo(map);  

You also point out that...

Using the same WMS source in OpenLayers (ol.source.TileWMS()) shows the data correctly

That is because OpenLayers 3 uses different defaults than Leaflet. A quick look at the OL3 source code reveals that its defaults image/png format and transparent request, whereas the source code for Leaflet assumes image/jpeg and not transparent.

Related Question