Swift 2 - 用户的当前位置在MKPolygon内



我正在尝试检查用户的当前位置是否在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
}

在尝试了几件不同的事情后,终于想通了。希望这对其他人有所帮助:

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
}

最新更新