Javascript – Leaflet z-index

javascriptleafletmapbox

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?

Best Answer

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);
    }

};

Related Topic