I would like to be able to change the order of the layers in Leaflet.
I tried implementing two Leaflet plugins in order to change the layer order.
First I tried leaflet-control-orderlayers, which seems to work, but does not support layerGroups, here is my filed bug.
Next I tried mapbbcode, which does support layerGroups, but does not seem to work or be maintained.
Does anyone have any suggestions for how to implement this feature?
Best Answer
You can do this in a couple ways (at least; this is how I do it):
layer.bringToFront()
andlayer.bringToBack()
but these will only do one layer at a time, and only pushes it to front or back, not in between. So you would need to put your layers in the desired order, start with the layer you want to be on bottom, and calllayer.bringToFront()
on each layer.You can also do this by removing and re-adding the layer. This seems sorta wasteful, but since the map must redraw when repositioning layers anyway, it is generally not that big of a deal.
Here is a fairly complex fiddle that illustrates the issue
Basically you remove all layers and then re-add them in ascending
z-index
order. So loop through all your overlay layers, and callmap.removeLayer(layer)
, then sort them by your desiredz-index
, then re-add them usinglayer.addTo(map)
.