在iOS中验证一个经纬度是否在MKPolygon内部

3

我将验证一个经纬度(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内的latlong:

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);
    }
}

它通常适用于正常情况,但是如果用户像下面这样绘制多边形,即MKpolygon的某些点相交并且在某些区域中填充颜色并清除某些区域的颜色:

enter image description here

如果我将清晰颜色部分的经纬度传递到MKPolygon内部,则应返回NO。但是,它返回YES。也就是说,if(CGPathContainsPoint(mpr , NULL, mapPointAsCGP, FALSE))为TRUE。

当MKPolygon之间存在交集时,如何解决此问题?最好建议在该清晰颜色区域中填充颜色。非常感谢您提供任何建议。

2个回答

1
这张图片似乎展示了奇偶填充规则。通过将最后一个参数指定为FALSE,您要求应用缠绕数规则来进行CGPathContainsPoint。尝试传递TRUE
有关两个规则的信息,请参见苹果的Quartz文档,特别是“填充路径”(略微低于中间位置)。

工作得非常好!非常感谢你,Tommy。 - Nazik

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)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接