2

How to find the largest polygon in GeoJSON of type multipolygon so that I can add a Leaflet tooltip to the largest polygon rather then a random polygon in multipolygon?

I have a Multipolygon and when adding a tootltip to it with Leaflet, the tooltip is attached to the first polygon or a random polygon in the multipolygon. I don't want it to be that way. I want to add tooltip to the largest polygon.

2
  • 2
    Iterate through polygons and calculate individual plygon area with turf.js library.
    – TomazicM
    Commented Sep 13, 2019 at 12:04
  • Thank you. it worked !!! what I have done now is finding the largest polygon with turf.area and adding tooltip to the centre with turf.centerOfMass. Commented Sep 19, 2019 at 12:01

1 Answer 1

4
max_area_polygon;
max_area = 0 ;

for(poly in (feature.geometry.coordinates)){                              
    polygon = turf.polygon((feature.geometry.coordinates)[poly])
    area = turf.area(polygon); 

    if(area > max_area){
        max_area = area
        max_area_polygon = polygon // polygon with the largest area
    }
}
center = turf.centerOfMass(max_area_polygon);

Center point rather than centroid because for some polygons may have centroids out of the boundaries

With this calculated center you can bind a tooltip as it returns a GeoJSON point

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.