如何确定注释是否在MKPolygonView(iOS)中

我试图计算一个特定的注释(如用户位置的蓝色圆圈)或MKPinAnnotation是否在MapView的MKPolygon图层内。

任何build议来实现这一目标?

以下内容将坐标转换为多边形视图中的CGPoint,并使用CGPathContainsPoint来testing该点是否位于path(可能是非矩形)中:

CLLocationCoordinate2D mapCoordinate = ...; //user location or annot coord MKMapPoint mapPoint = MKMapPointForCoordinate(mapCoordinate); MKPolygonView *polygonView = (MKPolygonView *)[mapView viewForOverlay:polygonOverlay]; CGPoint polygonViewPoint = [polygonView pointForMapPoint:mapPoint]; BOOL mapCoordinateIsInPolygon = CGPathContainsPoint(polygonView.path, NULL, polygonViewPoint, NO); 

这应该适用于MKOverlayPathView的子类的任何覆盖视图。 在示例中,您实际上可以用MKOverlayPathViewreplaceMKPolygonView。

稍微修改一下,可以在没有使用格式化为MKPolygon类的扩展名的MKMapView的情况下进行多边形中点/坐标的计算:

 //MKPolygon+PointInPolygon.h #import <Foundation/Foundation.h> #import <MapKit/MapKit.h> @interface MKPolygon (PointInPolygon) -(BOOL)coordInPolygon:(CLLocationCoordinate2D)coord; -(BOOL)pointInPolygon:(MKMapPoint)point; @end 

 //MKPolygon+PointInPolygon.m #import "MKPolygon+PointInPolygon.h" @implementation MKPolygon (PointInPolygon) -(BOOL)coordInPolygon:(CLLocationCoordinate2D)coord { MKMapPoint mapPoint = MKMapPointForCoordinate(coord); return [self pointInPolygon:mapPoint]; } -(BOOL)pointInPolygon:(MKMapPoint)mapPoint { MKPolygonRenderer *polygonRenderer = [[MKPolygonRenderer alloc] initWithPolygon:self]; CGPoint polygonViewPoint = [polygonRenderer pointForMapPoint:mapPoint]; return CGPathContainsPoint(polygonRenderer.path, NULL, polygonViewPoint, NO); } @end 

请享用!