isPointInPolygon static method

bool isPointInPolygon(
  1. ILatLong point,
  2. List<ILatLong> polygon
)

Determines if a point is inside or outside a polygon.

Uses the "ray casting" algorithm to determine if a point is inside a polygon.

Args: point: The point to test (ILatLong). polygon: A list of points (List

Returns: True if the point is inside the polygon, false otherwise.

Implementation

static bool isPointInPolygon(ILatLong point, List<ILatLong> polygon) {
  assert(polygon.length >= 3);
  // Check if the polygon is valid.
  // if (polygon.length < 3 || polygon.first != polygon.last) {
  //   throw ArgumentError(
  //       'The polygon must have at least 3 points and must be closed (first and last points are the same).');
  // }

  // Ray casting algorithm
  int intersectionCount = 0;
  final double pointX = point.longitude;
  final double pointY = point.latitude;

  ILatLong? previous;

  for (var current in polygon) {
    if (previous != null) {
      final double x1 = previous.longitude;
      final double y1 = previous.latitude;
      final double x2 = current.longitude;
      final double y2 = current.latitude;

      // Check if the ray intersects the current edge
      if (y1 <= pointY && y2 > pointY || y2 <= pointY && y1 > pointY) {
        // Calculate the intersection point of the ray with the current edge
        final double intersectionX = (x2 - x1) * (pointY - y1) / (y2 - y1) + x1;

        // If the intersection point is to the left of the test point, count it as an intersection
        if (pointX < intersectionX) {
          intersectionCount++;
        }
      }
    }
    previous = current;
  }

  // If the number of intersections is odd, the point is inside the polygon; otherwise, it's outside
  return intersectionCount % 2 == 1;
}