How to set the zIndex layer order for geoJson layers?

前端 未结 3 1565
[愿得一人]
[愿得一人] 2021-01-02 02:23

I would like to have certain layers to be always on top of others, no matter in which order they are added to the map. I am aware of bringToFront(), but it doe

3条回答
  •  情歌与酒
    2021-01-02 02:53

    For peoples who are searching about Z-Index

    All path layers (so all except for markers) have no z-index because svg layers have a fix order. The first element is painted first. So the last element is painted on top. @IvanSanchez described good why zIndex not working.

    You can control the order with layer.bringToBack() or layer.bringToFront().

    With that code you have more options to control the order of the layers.

    L.Path.include({
        getZIndex: function() {
            var node = this._path;
            var index = 0;
            while ( (node = node.previousElementSibling) ) {
                index++;
            }
            return index;
        },
        setZIndex: function(idx) {
            var obj1 = this._path;
            var parent = obj1.parentNode;
            if(parent.childNodes.length < idx){
                idx = parent.childNodes.length-1;
            }
            var obj2 = parent.childNodes[idx];
            if(obj2 === undefined || obj2 === null){
                return;
            }
            var next2 = obj2.nextSibling;
            if (next2 === obj1) {
                parent.insertBefore(obj1, obj2);
            } else {
                parent.insertBefore(obj2, obj1);
                if (next2) {
                    parent.insertBefore(obj1, next2);
                } else {
                    parent.appendChild(obj1);
                }
            }
        },
        oneUp: function(){
            this.setZIndex(this.getZIndex()+1)
        },
        oneDown: function(){
            this.setZIndex(this.getZIndex()-1)
        }
    });
    

    Then you can call

    • polygon.oneUp()
    • polygon.oneDown()
    • polygon.setZIndex(2)
    • polygon.getZIndex()
    • And now layergroup.setZIndex(2) are working

提交回复
热议问题