Leaflet z-index

11,368

Solution 1

Currently it's not available in the Leaflet API. Luckily if Leaflet is using SVG, all objects are DOM elements and we can simply change their order. Here's a sample code:

L.Path.prototype.setZIndex = function (index)
{
    var obj = $(this._container || this._path);
    if (!obj.length) return; // not supported on canvas
    var parent = obj.parent();
    obj.data('order', index).detach();

    var lower = parent.children().filter(function ()
    {
            var order = $(this).data('order');
            if (order == undefined) return false;
            return order <= index;
    });

    if (lower.length)
    {
            lower.last().after(obj);
    }
    else
    {
            parent.prepend(obj);
    }

};

Solution 2

Leaflet by default puts shapes ("overlays") and markers in different panes, with different z-index values:

Leaflet documentation / Map Panes

Source: https://leafletjs.com/reference-1.5.0.html#map-pane

Solution 3

Have a look at zIndexOffset, an option from the Marker class.

You can bind a function to the layeradd event to style each marker individually.

myLayer.on('layeradd', function (e) {
    var marker = e.layer;
    var zindex = 0;
    var feature = marker.feature;
    if (feature.geometry.type == 'Point') {
        marker.setStyle({
            'zIndexOffset': 3
        }
    });
});
Share:
11,368
Sebastian Nowak
Author by

Sebastian Nowak

Updated on June 14, 2022

Comments

  • Sebastian Nowak
    Sebastian Nowak almost 2 years

    I'm porting some Google Maps code to Leaflet (well, Mapbox actually). I have quite a lot of shapes (like rectangles, polygons) and markers on the map and I need the ability to adjust their order manually at any time, not just when adding them for the first time.

    In google maps there was a setZIndex method which allowed to adjust order of elements inside a pane (shapes were always below the markers). How can I do it in Leaflet? If it's not available in the api, what's the best way to implement it?