2

我正在尝试检查用户的当前位置是否在 MKPolygon 内。我创建了以下函数,但它对我的所有测试用例都返回 false。有什么我可能做错了吗?

func isCorrectRegion(coordinates: Array<JSON>, userLocation: CLLocationCoordinate2D) -> Bool {
    var newCoordinates: [CLLocationCoordinate2D] = []
    var mapPoints: [MKMapPoint] = []

    for(a):(JSON) in coordinates {
        let lat = a.arrayValue[1].double
        let long = a.arrayValue[0].double
        let location = CLLocationCoordinate2D(latitude: lat!, longitude: long!)
        newCoordinates.append(location)
    }

    for b in newCoordinates {
        let c: MKMapPoint = MKMapPointForCoordinate(b)
        mapPoints.append(c)
    }

    let polygon: MKPolygon = MKPolygon(points: &mapPoints, count: mapPoints.count)
    let polyRender: MKPolygonRenderer = MKPolygonRenderer(polygon: polygon)
    polyRender.invalidatePath()
    let target: MKMapPoint = MKMapPointForCoordinate(userLocation)
    let cgTarget: CGPoint = CGPoint(x: target.x, y: target.y)
    let isWithin = CGPathContainsPoint(polyRender.path, nil, cgTarget, false)

    return isWithin
}
4

1 回答 1

1

在尝试了一些不同的事情后终于弄明白了。希望这对其他人有帮助:

func isCorrectRegion(coordinates: Array<JSON>, userLocation: CLLocationCoordinate2D) -> Bool {
    var newCoordinates: [CLLocationCoordinate2D] = []
    var mapPoints: [MKMapPoint] = []
    let mpr: CGMutablePathRef = CGPathCreateMutable()

    for(a):(JSON) in coordinates {
        let lat = a.arrayValue[1].double
        let long = a.arrayValue[0].double
        let location = CLLocationCoordinate2D(latitude: lat!, longitude: long!)
        newCoordinates.append(location)
    }

    for b in newCoordinates {
        let c: MKMapPoint = MKMapPointForCoordinate(b)
        mapPoints.append(c)
    }

    for var p = 0; p<mapPoints.count; p++ {
        if p == 0 {
            CGPathMoveToPoint(mpr, nil, CGFloat(mapPoints[p].x), CGFloat(mapPoints[p].y))
        } else {
            CGPathAddLineToPoint(mpr, nil, CGFloat(mapPoints[p].x), CGFloat(mapPoints[p].y))
        }
    }

    let target: MKMapPoint = MKMapPointForCoordinate(userLocation)
    let cgTarget: CGPoint = CGPoint(x: target.x, y: target.y)
    let isWithin = CGPathContainsPoint(mpr, nil, cgTarget, false)

    return isWithin
}
于 2016-02-07T23:13:55.720 回答