Search code examples
javascriptangularleafletturfjs

How to find adjacent polygons in leaflet


I'm using leaflet and i want to found all layer adjacent to a selected layer. For example i have the following situation:

enter image description here

I would like to get adj1,adj2 and adj3 layers, I tried with intersection and contains method of leaflet but its doesn't work. Any suggestion about this?

Update 1

 layer.on('click', function(e) { 
  let isNeighboorAce = acesSelected.some(ace => { ace.poligon.getBounds().intersects(poligon.getBounds()) || ace.poligon.getBounds().contains(poligon.getBounds())});
  if(isNeighboorAce) {
    //Ci sono ace contigue quindi posso aggiungere
    acesSelected.push(aceSelected);
    layer.setStyle({fillOpacity: 0.4 , color: '#004691', weight: 3});
  } 
}

});


Solution

  • To know if two polygons are adjacent, you can call the getlatlngs method to get a list of points coordinates for each of them. Then use the distance method for each pair of points. If for any pair, the distance is 0, the 2 polygons are adjacent.

    Edit : Actually it is better to use pointToSegmentDistance. Because 2 adjacent polygons do not necessarily share a point. In that case, you loop through all the segments of the first polygon (using getlatlngs) and compute the distance to all the coordinates of the second polygon.