Search code examples
leaflet

How can I control the zindex of a leaflet layer?


I have a codepen at https://codepen.io/ericg_off/pen/qBoPQGX which demonstrates the issue.

I would like the marker to be drawn underneath the line.

How can I change the z-index of the layers to accomplish this?

Searching has suggested several potential solutions, but nothing appears to work.

HTML

<div id="map"></div> 

CSS

#map {
  height: 100vh;
}

#map >>> .my-icons {
  background-color: rgba(0, 255, 0, 0);
}

JS

var map = L.map("map", {
  // Set latitude and longitude of the map center (required)
  center: [38, -77],
  // Set the initial zoom level, values 0-18, where 0 is most zoomed-out (required)
  zoom: 5
});

// Create a Tile Layer and add it to the map
var tiles = new L.tileLayer(
  "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
  {
    attribution:
      '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    minZoom: 3,
    maxZoom: 8
  }
).addTo(map);


divIcon = L.divIcon({
  //html: '<i class="fa fa-map-marker fa-1x"></i>',
  html: '<i class="fa fa-star fa-1x"></i>',
  className: 'my-icons'
})

const markerLayer = L.layerGroup().addTo(map);
const lineLayer = L.layerGroup().addTo(map);

// markerLayer.setZIndex(-1000)
// markerLayer.bringToBack();

const from = [38, -77];
const to = [38, -100];
const fromMarker = L.marker(from, { icon: divIcon } ).addTo(lineLayer);
const line = L.polyline([from, to], { color: "green", weight: 1 }).addTo(markerLayer);

Solution

  • The tutorial on panes explains how to change the zIndex of a pane.

    After reading the documentation on Panes and learning that the marker pane has a zindex of 600 and the overlay pane (where the lines are drawn) has a index of 400, I just needed to change the marker pane to a index of 300.

    map.getPane('markerPane').style.zIndex = 300;
    

    Updated the codepen with the answer.