perand
perand

Reputation: 15

OpenStreetMap tile opacity

is there a way to set the opacity of just the tiles using leaflet and OpenStreetMap? I want the map to have 50% opacity, but keep 100% opacity on the markers.

Setting opacity like this, does not work:

var bkgLayer = L.tileLayer.grayscale('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');

    var map = new L.Map("map", {
                center: new L.LatLng(-31.4, 50.9),
                scrollWheelZoom: false,
                  zoomControl: false,
                  zoom: 5,
                  opacity: 0.5,
                  layers: bkgLayer
              }); 

Upvotes: 1

Views: 1448

Answers (2)

ghybs
ghybs

Reputation: 53185

Normal Leaflet Tile Layer (Grid Layer) has the opacity option.

https://leafletjs.com/reference-1.7.1.html#gridlayer-opacity

In your case you are using a special Tile Layer with Leaflet.TileLayer.Grayscale plugin.

However it properly extends the normal Tile Layer behaviour, and its code does not seem to make it incompatible with the opacity option. Therefore it should simply work:

var bkgLayer = L.tileLayer.grayscale('urlTemplate', {
  opacity: 0.75
});

Upvotes: 1

jharris711
jharris711

Reputation: 612

You can use document.querySelector to access the Leaflet tile pane and set the opacity through style:

const element = document.querySelector(
  '.leaflet-tile-pane'
).style.opacity = 0.5;

Here is a demo I put together on StackBlitz showing how to use Leaflet-Slider to adjust the opacity of the tile layer without altering the markers.

Upvotes: 2

Related Questions