我验证一个latlong(CLLocationCoordinate2D
)是否在MKMapview上绘制的MKPolygon内。
我使用下面的代码在MKMapview上绘制MKPolygon,
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;
}
我使用
验证MKPolygon中的latlongCLLocationCoordinate2D 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);
}
}
它适用于正常情况,但如果用户绘制如下的多边形,即MKpolygon有一些点相交,颜色在某些区域填充,并且某些区域颜色清晰。
如果我通过MKPolygon内部的透明颜色部分的latlong,它应该返回NO。但是,它返回YES。即if(CGPathContainsPoint(mpr , NULL, mapPointAsCGP, FALSE))
为真。
如果MKPolygon之间有交集,我该如何解决这个问题?如果有人建议在那个清晰的颜色区域填充颜色,情况会更好。任何建议都将不胜感激。
答案 0 :(得分:1)
显示的图片似乎展示了偶数填充规则。通过将FALSE
指定为CGPathContainsPoint
的最终参数,您已要求它应用绕组编号规则。尝试传递TRUE
。
有关teo规则的信息,请参阅Apple's Quartz documentation,特别是“填充路径”(略低于一半)。
答案 1 :(得分:0)
Swift 3.0实施:
func checkIf(polygon: MKPolygon, contains point: CGPoint) -> Bool {
let path = CGMutablePath()
let polygonPoints = polygon.points()
for index in 0..<polygon.pointCount {
let mp = polygonPoints[index]
if index == 0 {
path.move(to: CGPoint(x: mp.x, y: mp.y))
} else {
path.addLine(to: CGPoint(x: mp.x, y: mp.y))
}
}
return path.contains(point)
}