4

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

1 Answer 1

7

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/

1
  • 1
    or "layeradd" when working with geometry layers, nice solution!
    – chrismarx
    May 2, 2017 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.