2010-12-04 42 views

回答

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

這將工作在有孔(內部多邊形)MKPolygons? – 2011-02-09 16:12:06

+7

@Greg Combs:如果多邊形(或覆蓋路徑)有孔,如果查詢的點位於孔中,則CG​​PathContainsPoint將返回NO。 – Anna 2011-02-09 16:40:07

9

上面稍加修改,以做點計算多邊形中不使用的MKMapView的格式化的一個擴展MKPolygon類:

//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 

享受!

相關問題