我正在尝试计算特定注释(比如用户位置的蓝色圆圈)或MKPinAnnotation是否在地图视图上的MKPolygon图层内。
有什么建议实现这个功能吗?
有什么建议实现这个功能吗?
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。
//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
享受吧!
[MKPolygonView initWithPolygon]
在iOS 7中已经被弃用,但可以使用MKPolygonRenderer
来替代它。 - Trasplazio Garzuglio
path
属性似乎会错误地返回NULL,导致上述方法失败。有一个解决方法,请参见https://dev59.com/Y2Mk5IYBdhLWcg3wvAVo。 - user467105