Search code examples
javascriptleafletngx-leaflet

Leaflet: Get inner-most layer on mouse click and mouse hover on intersecting rectangles


I am trying to display a set of rectangles on a map. I am able to draw all of them using:

var rec = L.rectangle(bounds, {color: "#ff7800", weight: 1})
                .bindTooltip('Z1', { sticky: true}).addTo(map);

However, when I hover over the rectangles, the tooltip is shown only for the outer-most rectangle. Also, in click event, only the outer-most rectangle is selected. (Note that larger rectangles can be layered over smaller ones)

Given this situation - how do I show the tooltip correctly and retreive the proper layer on click event?

Stackblitz : click here


Solution

  • The problem is Z2 rectangle lies behind the Z1 (Z1 contains Z2).

    data.sort((a, b) => {
       return L.bounds(a.bounds).contains(b.bounds) ? -1 : 1;
    });
    

    Here I sorted the bounds using contains method

    Stackblitz