Leaflet z-index

2019-07-23 07:35发布

问题:

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?

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

};



回答2:

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