2010-12-04 8 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のサブクラスです。この例では、実際にはMKPolygonViewをMKOverlayPathViewに置き換えることができます。

+1

ホール(内部ポリゴン)を持つMKポリゴンでこれは機能しますか? –

+7

@Greg Combs:ポリゴン(またはオーバーレイパス)に穴がある場合、照会されたポイントが穴にある場合、CGPathContainsPointはNOを返します。 – Anna

+0

@AnnaKarenina - この同じmapCoordinateIsInPolygonの値は、MKPolygonではマップビューではないシナリオでどのように決定するのですか? (私が持っているものは全て座標のセットですが、ビューの必要はありません) –

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 

お楽しみください!

+1

'[MKPolygonView initWithPolygon]'はiOS 7では非推奨ですが、 'MKPolygonRenderer'で置き換えることができます。 –

+0

ありがとう!私は今iOS7のコードを更新しました。 – capikaw

関連する問題