leafletreact-leafleth3

H3 - How to get center lat long of a multi polygon?


I have created Multi polygons using h3SetToMultiPolygon from the list of H3 cell ids as shown below:

enter image description here

Now I want to get the center (I know it's not a perfect shape to get the center, but a rough one should be fine) of the Multi Polygon which I am unable to get using any H3 or leaflet methods. I want to show a marker at the center of the boundary of the multi polygons as shown below roughly:

enter image description here

Any help would be appreciated. Here is my code:

const clusterBoundaryCoordinates = [];
clusters?.forEach((element) => {
  clusterBoundaryCoordinates.push(
    h3.h3SetToMultiPolygon(element.cellIdsArr, true)
  );
});

Solution

  • I found the solution. I didn't notice earlier that to find the center, I can utilize the lat longs which I receive when I do h3SetToMultiPolygon (it returns the lat long in reverse order).

    const clusterBoundaryCoordinates = [];
    clusters?.forEach((element) => {
      clusterBoundaryCoordinates.push(
        h3.h3SetToMultiPolygon(element.cellIdsArr, true);       //it returns the latlong in reverse order, so need to reverse it
      );
    });
    
    const getCentroid = (arr) => {
      return arr.reduce(
        (x, y) => {
          return [x[0] + y[0] / arr.length, x[1] + y[1] / arr.length];
        },
        [0, 0]
      );
    };
    const centroid = getCentroid(clusterBoundaryCoordinates);