GeoJSON – Largest Polygon Inside a Multipolygon Using Leaflet

geojsonleafletpolygontooltip

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.

Best Answer

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