Search code examples
csssvgleafletvector-tiles

Styling an SVG tile layer with CSS in Leaflet


I use Leaflet to display a vector tile layer, like this:

var tiles = L.tileLayer('mytiles/{z}/{x}/{y}.svg', {
    renderer: L.svg(),
    continuousWorld: true,
    noWrap: true,
    minZoom: 0,
    maxZoom: 10,
})

The elements of my tiles have CSS classes, such as <rect class="country-ES" ...></rect>, so I would like to style them in my CSS:

.country-ES {
  fill: red !important;
}

However, the tiles do not seem to be affected by these CSS instructions. And I do not know how to debug this as the tiles cannot be inspected by the web developper tools of Chrome or Firefox.

Any idea how that can be achieved?


Solution

  • Setting the renderer: L.svg() in the tiles has no effect (this is meant for the overlay elements in the map).

    I had to force Leaflet to display the tiles as embedded SVG, like this:

    tiles.createTile = function (coords, done) {
        var tile = document.createElement('div');
    
        tile.setAttribute('role', 'presentation');
    
        $.get(this.getTileUrl(coords),
             success=function(data) {
                 tile.appendChild(data.firstChild);
                 done(null, tile);
        }).fail(function(error) {
                 done(error, tile);
        });
    
        return tile;
    };
    

    And then it worked!