Alex G.
Alex G.

Reputation: 87

Leaflet overlay order (points, lines, and polygons)

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.

Upvotes: 5

Views: 5374

Answers (1)

ghybs
ghybs

Reputation: 53185

The 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.net/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.com/questions/166252/geojson-layer-order-in-leaflet-0-7-5/167904#167904

Upvotes: 7

Related Questions