Vector Layer Visibility – How to Keep on Top in Leaflet

leaflet

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);

JSFIDDLE link

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 and layerTWO are added or removed at a later moment, and the bringToFront() effect is lost.

You would simply need to re-execute bringToFront() any time layerONE (or any other vector layer you may have, and that you want shown behind your layerTWO) is added to the map by the Layers Control.

Typically, listen to "overlayadd" event and bring to front your "top" vector layer again:

map.on("overlayadd", function (event) {
  layerTWO.bringToFront();
});

Updated JSFiddle: https://jsfiddle.net/htb5afed/3/