containsLocationAtLatLng static method

bool containsLocationAtLatLng(
  1. num latitude,
  2. num longitude,
  3. List<LatLng> polygon,
  4. bool geodesic,
)

Computes whether the given point lies inside the specified polygon. The polygon is always considered closed, regardless of whether the last point equals the first or not. Inside is defined as not containing the South Pole -- the South Pole is always outside. The polygon is formed of great circle segments if geodesic is true, and of rhumb (loxodromic) segments otherwise.

Implementation

static bool containsLocationAtLatLng(
    num latitude, num longitude, List<LatLng> polygon, bool geodesic) {
  if (polygon.isEmpty) {
    return false;
  }

  final lat3 = MathUtil.toRadians(latitude);
  final lng3 = MathUtil.toRadians(longitude);
  final prev = polygon.last;
  var lat1 = MathUtil.toRadians(prev.latitude);
  var lng1 = MathUtil.toRadians(prev.longitude);
  var nIntersect = 0;

  for (final point2 in polygon) {
    final dLng3 = MathUtil.wrap(lng3 - lng1, -pi, pi);
    // Special case: point equal to vertex is inside.
    if (lat3 == lat1 && dLng3 == 0) {
      return true;
    }
    final lat2 = MathUtil.toRadians(point2.latitude);
    final lng2 = MathUtil.toRadians(point2.longitude);
    // Offset longitudes by -lng1.
    if (_intersects(lat1, lat2, MathUtil.wrap(lng2 - lng1, -pi, pi), lat3,
        dLng3, geodesic)) {
      ++nIntersect;
    }
    lat1 = lat2;
    lng1 = lng2;
  }
  return (nIntersect & 1) != 0;
}