我想知道水龙头是否在MKPolygon中。
我有一个MKPolygon:
CLLocationCoordinate2D points[4];
points[0] = CLLocationCoordinate2DMake(41.000512, -109.050116);
points[1] = CLLocationCoordinate2DMake(41.002371, -102.052066);
points[2] = CLLocationCoordinate2DMake(36.993076, -102.041981);
points[3] = CLLocationCoordinate2DMake(36.99892, -109.045267);
MKPolygon* poly = [MKPolygon polygonWithCoordinates:points count:4];
[self.mapView addOverlay:poly];
//create UIGestureRecognizer to detect a tap
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(foundTap:)];
tapRecognizer.numberOfTapsRequired = 1;
tapRecognizer.numberOfTouchesRequired = 1;
[self.mapView addGestureRecognizer:tapRecognizer];
它只是科罗拉多州的基本轮廓。
我设置了经纬度/经度转换的设置:
-(IBAction)foundTap:(UITapGestureRecognizer *)recognizer
{
CGPoint point = [recognizer locationInView:self.mapView];
CLLocationCoordinate2D tapPoint = [self.mapView convertPoint:point toCoordinateFromView:self.view];
}
但是我不确定如果我的点击点在MKPolygon内,该如何进行技术处理。似乎没有一种方法可以执行此检查,所以我想我需要将MKPolygon转换为CGRect并使用CGRectContainsPoint。
MKPolygon具有.points属性,但我似乎无法将其撤回。
有什么建议?
编辑:
以下两种解决方案都可以在iOS 6或更低版本中使用,但在iOS 7中可以使用。在iOS 7中,
polygon.path
属性始终返回NULL
。安娜女士很友善地提供a solution in another SO question here。它涉及从多边形点创建您自己的路径以传递到CGPathContainsPoint()
。我的多边形的图片:
最佳答案
我创建了这个MKPolygon类别,以防有人使用。似乎运作良好。您必须考虑内部多边形(即多边形中的孔):
@interface MKPolygon (PointInPolygon)
-(BOOL) pointInPolygon:(CLLocationCoordinate2D) point mapView: (MKMapView*) mapView;
@end
@implementation MKPolygon (PointInPolygon)
-(BOOL) pointInPolygon:(CLLocationCoordinate2D) point mapView: (MKMapView*) mapView {
MKMapPoint mapPoint = MKMapPointForCoordinate(point);
MKPolygonView * polygonView = (MKPolygonView*)[mapView viewForOverlay:self];
CGPoint polygonViewPoint = [polygonView pointForMapPoint:mapPoint];
return CGPathContainsPoint(polygonView.path, NULL, polygonViewPoint, NO) &&
![self pointInInteriorPolygons:point mapView:mapView];
}
-(BOOL) pointInInteriorPolygons:(CLLocationCoordinate2D) point mapView: (MKMapView*) mapView {
return [self pointInInteriorPolygonIndex:0 point:point mapView:mapView];
}
-(BOOL) pointInInteriorPolygonIndex:(int) index point:(CLLocationCoordinate2D) point mapView: (MKMapView*) mapView {
if(index >= [self.interiorPolygons count])
return NO;
return [[self.interiorPolygons objectAtIndex:index] pointInPolygon:point mapView:mapView] || [self pointInInteriorPolygonIndex:(index+1) point:point mapView:mapView];
}
@end
关于ios - 检测点是否在MKPolygon覆盖内,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10109677/