I'm working with the Leaflet.StyledLayerControl plugin and would like to set my layers so that polygons always get pushed to the back, lines above the polygons, and points above the lines.
I have searched for solutions here but most refer to tilelayers or map panes (which I think only work with another version of leaflet 1.0).
I want to be able to toggle lines on and off and have them always be below points (same with polygons below polylines).
I'm guessing I have to do something with setZIndex
or bringToFront()
but i'm not sure where to start.
Any help would be appreciated. Thanks.
I'm working with the Leaflet.StyledLayerControl plugin and would like to set my layers so that polygons always get pushed to the back, lines above the polygons, and points above the lines.
I have searched for solutions here but most refer to tilelayers or map panes (which I think only work with another version of leaflet 1.0).
I want to be able to toggle lines on and off and have them always be below points (same with polygons below polylines).
I'm guessing I have to do something with setZIndex
or bringToFront()
but i'm not sure where to start.
Any help would be appreciated. Thanks.
Share Improve this question edited Jul 26, 2016 at 22:48 Tomislav Stankovic 3,12617 gold badges37 silver badges43 bronze badges asked Jul 26, 2016 at 20:27 Alex G.Alex G. 871 silver badge8 bronze badges1 Answer
Reset to default 7The easy solution is really to use Leaflet 1.0, which provides you with map.createPane("paneName")
functionality. So you create like "polygonsPane", "linesPane" and "pointsPane", that you specify to each of your vector / shape layers using their pane
option.
Once set, you can add / remove them to / from map, and they will always be inserted in the specified pane, hence respecting the pane's order.
// Create necessary panes in correct order (i.e. "bottom-most" first).
map.createPane("polygonsPane");
map.createPane("linesPane");
map.createPane("pointsPane");
L.polygon([/* coords */], { pane: "polygonsPane" }).addTo(map);
L.polyline([/* coords */], { pane: "linesPane" }).addTo(map);
L.circleMarker([/* coords */], { pane: "pointsPane" }).addTo(map);
Demo: https://jsfiddle/3v7hd2vx/51/
With Leaflet 0.7, you know that all vector layers are part of the same SVG container, being appended when added to map, hence they appear on top of all previously added vectors. Then you have to use bringToFront()
and/or bringToBack()
to re-sort them to whatever order you need.
You might be interested in that post for that case: https://gis.stackexchange./questions/166252/geojson-layer-order-in-leaflet-0-7-5/167904#167904