Search code examples
javascriptleafletz-indexgeojson

Leaflet Circle Z-Index


I'm drawing a route using Leaflet.

The route is divided in frames, each frame is marked with a circle and on hover event the frame shows up with as an opaque overlay over the route.

enter image description here

The issue is that the circle is drawn behind the frame overlay but I want it on top of everything (on the z-axis).

I've searched and tried everything I've found but I can't make it stay on top.. What can I do?

This is what I'm doing:

L.geoJson(route, {
  style: function(feat) {
    return {
      weight: 10,
      opacity: 1,
      cursor: 'pointer',
      color: 'transparent',
      className: 'journey-frame'    
    }
  },
  onEachFeature(feat, layer) {
    var c = layer.getBounds().getCenter()
    var color = getColor()
    var circle = L.circle(c, {
      color: 'black', 
      weight: 2, 
      radius: 3,
      fill: true, 
      fillColor: color,
      fillOpacity: 1,
      className: 'frame-circle',
      zIndexOffset: 1000 // first attempt to place circle on top. Not working
    })

    // second attempt. Not working
    circle.bringToFront()

    // Change layer color to show frame
    layer.on('mouseover', function() {
      layer.setStyle({color: '#ddd', opacity: 0.8});
    })

    // Change layer color to hide frame
    layer.on('mouseout', function() {
      layer.setStyle({color: 'transparent'});
    })
  }
}).addTo(mymap)

In my CSS file

.frame-circle {
    z-index: 1000; /* tried also this but still nothing */
}

Solution

  • You can use bringToFront() only once the layer you use it on is already on map (i.e. outside the onEachFeature function).

    In your case, you have to wait for the L.geoJson().addTo(map), then retrieve your layer (circle), and now you can use bringToFront().

    The reason is very simple: this method acts on the layer's parent node to append the layer at the end (or as the first child in the case of bringToBack()). If the layer is not added to map, it is not inserted in DOM and it does not have any parent container where it can be re-ordered (appended / inserted).