Reputation: 183
I'm struggling with finding out if a MKPolygon intersects with a MKCircle.
This is my situation: I have a map filled with regions. Now the user can set a pin on the map, from where I draw an MKCircle with the pin's location as the center. Now I want to know if this circle overlaps with some region already on the map.
My idea is to check every point of the polygons if they lie within the circle using the CGPathContainsPoint method.
This is my code:
//the circle for the location filter
MKCircleView *circleView = (MKCircleView *)[map viewForOverlay:self.sfvc.pinCircle];
//loop all regions
for (MKPolygon *region in regions){
BOOL mapCoordinateIsInPolygon = FALSE;
//loop all point of this region
for (int i = 0; i < region.pointCount; i++) {
MKMapPoint point = region.points[i];
CGPoint circleViewPoint = [circleView pointForMapPoint:point];
mapCoordinateIsInPolygon = CGPathContainsPoint(circleView.path, NULL, circleViewPoint, NO);
}
if (mapCoordinateIsInPolygon) {
NSLog(@"YES! At least one point of the poly lies within the circle");
}
}
Unfortunately I get unpredictable results - that do not make any sense. Any idea what I'm doing wrong? Is there another way to do what I want?
My code is partly from How to determine if an annotation is inside of MKPolygonView (iOS)
Note: I know that my solution relies on the assumption that the regions / paths have enough points defined so that at least one point will fall in the circle.
Thanks in advance,
Cheers, pawi
Upvotes: 2
Views: 3734
Reputation: 1683
CLLocationCoordinate2D newCoord ;
newCoord.latitude = [[firDict objectForKey:@"Latitude"] floatValue];
newCoord.longitude = [[firDict objectForKey:@"Longitude"] floatValue];
[self pointInsideOverlay:newCoord MyOverlay:Curoverlay];
-(void)pointInsideOverlay:(CLLocationCoordinate2D )tapPoint MyOverlay:(id <MKOverlay>)overlay
{
isInside = FALSE;
MKMapPoint mapPoint = MKMapPointForCoordinate(tapPoint);
CGMutablePathRef mpr = CGPathCreateMutable();
MKMapPoint *polygonPoints = myPolygon.points;
for (int p=0; p < myPolygon.pointCount; p++)
{
MKMapPoint mp = polygonPoints[p];
if (p == 0)
CGPathMoveToPoint(mpr, NULL, mp.x, mp.y);
else
CGPathAddLineToPoint(mpr, NULL, mp.x, mp.y);
}
CGPoint mapPointAsCGP = CGPointMake(mapPoint.x, mapPoint.y);
BOOL pointIsInPolygon = CGPathContainsPoint(mpr, NULL, mapPointAsCGP, FALSE);
if (pointIsInPolygon)
{
isInside = TRUE;
}
CGPathRelease(mpr);
}
Upvotes: 0
Reputation: 183
Well, I figured it out finally. The code above should work as is, except that there is a missing break statement in the loop. The code as is returns only the last checked point of the poly. Inserting a test to mapCoordinateIsInPolygon and then a break statement in the inner loop leaves the loop as soon as the first test is positive, thus giving the correct result. ;-)
Upvotes: 3