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

时间:2010-12-04 15:03:52

标签: ios mkmapview mkpolygonview

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

有任何建议可以达到这个目的吗?

2 个答案:

答案 0 :(得分:37)

以下内容将坐标转换为多边形视图中的CGPoint,并使用CGPathContainsPoint测试该点是否在路径中(可能是非矩形):

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的子类的任何叠加视图。实际上,您可以使用MKOverlayPathView替换MKPolygonView。

答案 1 :(得分:9)

上面略微修改,无需使用格式化为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

享受!