MKPolygon - How to determine if a CLLocationCoordinate2D is in a CLLocationCoordinate2D polygon?

前端 未结 5 855
春和景丽
春和景丽 2021-01-15 06:06

I have the swift code below that draws a polygon and drops an annotation on MKMapView. I am trying to figure out how i could identify if the annotation\'s coordinate is with

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-15 06:32

    - (BOOL)isPoint:(MKMapPoint)point insidePolygon:(MKPolygon *)poly {
      MKMapPoint *a =  poly.points;
      BOOL isInsidePolygon = NO;
    
      double testx = point.x;
      double testy = point.y;
    
      NSUInteger i = 0, j = 0, nvert = [poly pointCount];
    
      for (i = 0,  j = nvert - 1; i < nvert; j = i++) {
        if (((a[i].y >= testy) != (a[j].y >= testy)) &&
            (testx <= (a[j].x - a[i].x) * (testy - a[i].y) / (a[j].y - a[i].y) + a[i].x)) {
              isInsidePolygon = !isInsidePolygon;
            }
      }
    
      return isInsidePolygon;
    }
    

    Because the points x y are in Mercator projection coordinates, this makes sense and you don't need to convert to spherical coordinates for the calculation.

    Why this is a correct calculation here.

    EDIT: updated so that the calculation also considers a point on the line as inside the poly.

提交回复
热议问题