I'm trying to calculate if a specific annotation(like the blue circle of the user location) or a MKPinAnnotation is inside an MKPolygon layer on the mapview.
Any advice to achieve this?
I'm trying to calculate if a specific annotation(like the blue circle of the user location) or a MKPinAnnotation is inside an MKPolygon layer on the mapview.
Any advice to achieve this?
The following converts the coordinate to a CGPoint in the polygon view and uses CGPathContainsPoint to test if that point is in the path (which may be non-rectangular):
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);
This should work with any overlay view that is a subclass of MKOverlayPathView. You can actually replace MKPolygonView with MKOverlayPathView in the example.
path
property seems to incorrectly return NULL making the above approach fail. For a workaround, see #19015426. –
Chara [MKPolygonView initWithPolygon]
is deprecated in iOS 7 but can be replaced with MKPolygonRenderer
. –
Pasteurism Slightly modified above to do calculations for points/coordinates in polygons without the use of a MKMapView formatted as an extension to MKPolygon class:
//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
Enjoy!
[MKPolygonView initWithPolygon]
is deprecated in iOS 7 but can be replaced it with MKPolygonRenderer
. –
Pasteurism © 2022 - 2024 — McMap. All rights reserved.