How do I keep a layer on top of my other layers despite the order it is toggled by the user? In this example, I've set up two layers named layerONE and layerTWO.
How do I keep my layerTWO (red square in this example) on top of layerONE at all times?
I tried this but it didn't work (notice my bringToFront method):
var layerONE = L.geoJson(layerOne).bindPopup('this is layer one!');
var layerTWO = L.geoJson(layerTwo, {
style: {color: 'red'}
}).bindPopup('this is layer two!').bringToFront();
var overlays = {
"Layer One": layerONE,
"Layer Two": layerTWO
};
L.control.layers(null, overlays).addTo(map);
Best Answer
The
bringToFront()
method changes the order of your layer only at the time it is executed.When the user clicks on the Layers Control, your
layerONE
andlayerTWO
are added or removed at a later moment, and thebringToFront()
effect is lost.You would simply need to re-execute
bringToFront()
any timelayerONE
(or any other vector layer you may have, and that you want shown behind yourlayerTWO
) is added to the map by the Layers Control.Typically, listen to
"overlayadd"
event and bring to front your "top" vector layer again:Updated JSFiddle: https://jsfiddle.net/htb5afed/3/