containsLocation static method

bool containsLocation(
  1. double lat,
  2. double lng,
  3. List<LatLng> polygon, [
  4. bool geodesic = false,
])

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 containsLocation(double lat, double lng, List<LatLng> polygon,
    [bool geodesic = false]) {
  final length = polygon.length;
  if (length == 0) return false;

  final lat3 = radians(lat);
  final lng3 = radians(lng);
  final prev = polygon[length - 1];
  var lat1 = radians(prev.latitude);
  var lng1 = radians(prev.longitude);

  var nIntersect = 0;
  for (final point2 in polygon) {
    final dLng3 = _wrap(lng3 - lng1, -pi, pi);
    // Special case: point equal to vertex is inside.
    if (lat3 == lat1 && dLng3 == 0) return true;

    final lat2 = radians(point2.latitude);
    final lng2 = radians(point2.longitude);
    // Offset longitudes by -lng1.
    if (intersects(
        lat1, lat2, _wrap(lng2 - lng1, -pi, pi), lat3, dLng3, geodesic)) {
      ++nIntersect;
    }

    lat1 = lat2;
    lng1 = lng2;
  }

  return (nIntersect & 1) != 0;
}