centroid property

List<double> centroid

Returns the geographic center (centroid) of a polygon, including any holes.

The centroid is calculated by taking into account the area of the outer polygon and subtracting the areas of any holes.

Note: The centroid may not necessarily lie within the polygon, especially if the polygon has a complex shape or includes holes.

Returns: A two-element list longitude, latitude representing the centroid coordinates.

Throws an ArgumentError if there are fewer than three points provided to calculate the area of a polygon.

Reference: Wikipedia

Implementation

List<double> get centroid {
  var coords = <List<List<double>>>[];
  for (final ring in coordinates) {
    final transformedRing = <List<double>>[];

    for (final point in ring) {
      final List<double> transformedPoint =
          convertToWebMercator(point[0], point[1]);
      transformedRing.add(transformedPoint);
    }

    coords.add(transformedRing);
  }
  var outer = coords.first;
  var n = outer.length;
  double cx = 0;
  double cy = 0;
  for (int i = 0; i < n; i++) {
    double x1 = outer[i][1];
    double y1 = outer[i][0];
    double x2 = outer[(i + 1) % n][1];
    double y2 = outer[(i + 1) % n][0];
    double f = x1 * y2 - x2 * y1;
    cx += (x1 + x2) * f;
    cy += (y1 + y2) * f;
  }
  double a = getPlanarArea(outer) * 6;
  var c = convertFromWebMercator(cy.abs() / a, cx.abs() / a);
  return c;
}