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

Posted

技术标签:

【中文标题】Swift 2 - 用户的当前位置在 MKPolygon 内【英文标题】:Swift 2 - User's Current Location is inside MKPolygon 【发布时间】:2016-02-06 08:31:14 【问题描述】:

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

【问题讨论】:

【参考方案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

【讨论】:

以上是关于Swift 2 - 用户的当前位置在 MKPolygon 内的主要内容,如果未能解决你的问题,请参考以下文章

如何在swift 3.0中计算用户从当前位置行进的距离

如何使用 Swift 显示自定义注释,即使它位于用户的当前位置

在执行代码之前等待用户关闭模态视图(Swift 2.0)

谷歌地图中的当前位置与swift

如何使用swift获取appdelegate中的当前位置

在谷歌地图中保留用户位置中心 - Swift