getPlanarArea function

double getPlanarArea(
  1. List<List<double>> ring
)

Returns the area of a ring with planar coordinates.

The ring is represented as a list of points. Each point is a list of two doubles (x, y).

The area is computed using the method of signed areas, also known as the shoelace formula. The formula calculates the signed areas of the trapezoids under the lines between consecutive points. The formula requires the points to be ordered either clockwise or counter-clockwise.

The absolute value of the signed area gives the area of the ring.

Throws ArgumentError if the input is not a list of at least three points.

Example:

var ring = [
  [0.0, 0.0],
  [1.0, 0.0],
  [1.0, 1.0],
  [0.0, 1.0]
];
print(getPlanarArea(ring));  // prints: 1.0

ring: A list of points representing the ring. Each point is a list of two doubles (x, y).

Returns the area of the ring.

Implementation

double getPlanarArea(List<List<double>> ring) {
  if (ring.length < 4 || !numListEquals(ring.first, ring.last)) {
    throw ArgumentError(
        "Input must be a list of at least four points, where the first and last points are the same.");
  }

  int n = ring.length;
  double a = 0;
  for (int i = 0; i < n; i++) {
    double x1 = ring[i][0];
    double y1 = ring[i][1];
    double x2 = ring[(i + 1) % n][0];
    double y2 = ring[(i + 1) % n][1];
    a += x1 * y2 - x2 * y1;
  }
  return (a / 2).abs();
}