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 does not meet my requirements. I would like to set the zIndex dynamically based on properties.
Leaflet has the method setZIndex()
, but this apparently does not work for geoJson layers:
https://jsfiddle.net/jw2srhwn/
Any ideas?
Cannot be done for vector geometries.
zIndex
is a property of HTMLElement
s, and vector geometries (lines and polygons) are rendered as SVG elements, or programatically as <canvas>
draw calls. Those two methods have no concept of zIndex
, so the only thing that works is pushing elements to the top (or bottom) of the SVG group or <canvas>
draw sequence.
Also, remind that L.GeoJSON
is just a specific type of L.LayerGroup
, in your case containing instances of L.Polygon
. Furthermore, if you read Leaflet's documentation about the setZIndex()
method on L.LayerGroup
:
Calls
setZIndex
on every layer contained in this group, passing the z-index.
So, do L.Polygon
s have a setZIndex()
method? No. So calling that in their containing group does nothing. It will have an effect on any L.GridLayer
s contained in that group, though.
Coming back to your problem:
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.
Looks like the thing you're looking for is map panes. Do read the map panes tutorial.