I'm validating whether a latlong(CLLocationCoordinate2D
) is inside a MKPolygon which is drawn on the MKMapview.
I'm using below code to draw MKPolygon on a MKMapview,
MKPolygon *polygon = [MKPolygon polygonWithCoordinates:coordinates count:count];
[mapviewcontroller.mapview addOverlay:polygon];
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
MKPolygonRenderer *renderer = [[MKPolygonRenderer alloc] initWithPolygon:overlay];
renderer.fillColor = [[UIColor grayColor] colorWithAlphaComponent:0.2];
renderer.strokeColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
renderer.lineWidth = 2;
return renderer;
}
I'm validating the latlong inside MKPolygon using,
CLLocationCoordinate2D sampleLocation = CLLocationCoordinate2DMake(13,80);//13,80 is the latlong of clear colored area of the MKPolygon in the below image.
MKMapPoint mapPoint = MKMapPointForCoordinate(sampleLocation);
CGPoint mapPointAsCGP = CGPointMake(mapPoint.x, mapPoint.y);
for (id<MKOverlay> overlay in mapview.overlays) {
if([overlay isKindOfClass:[MKPolygon class]]){
MKPolygon *polygon = (MKPolygon*) overlay;
CGMutablePathRef mpr = CGPathCreateMutable();
MKMapPoint *polygonPoints = polygon.points;
for (int p=0; p < polygon.pointCount; p++){
MKMapPoint mp = polygonPoints[p];
if (p == 0)
CGPathMoveToPoint(mpr, NULL, mp.x, mp.y);
else
CGPathAddLineToPoint(mpr, NULL, mp.x, mp.y);
}
if(CGPathContainsPoint(mpr , NULL, mapPointAsCGP, FALSE)){
isInside = YES;
}
CGPathRelease(mpr);
}
}
It is working great for normal cases, but if the user draws the polygon like below ie, MKpolygon has some points intersecting and the color is filled in some area and clear color in some area.
If I pass the latlong of the clear colored portion inside the MKPolygon, it should return NO. But, it is returning YES. ie, if(CGPathContainsPoint(mpr , NULL, mapPointAsCGP, FALSE))
is TRUE.
How can I fix this issue while the MKPolygon has intersection in between? It's better if someone suggests to fill the color in that clear color area. Any suggestions would be greatly appreciated.
The picture shown appears to demonstrate the even-odd fill rule. By specifying FALSE
as the final parameter to CGPathContainsPoint
you've asked it to apply the winding number rule. Try passing TRUE
.
For information on the teo rules see Apple's Quartz documentation, particularly 'Filling a Path' (slightly less than halfway down).