【问题标题】:MKMapView get distance between coordinates on customized routeMKMapView 获取自定义路线上坐标之间的距离
【发布时间】:2015-02-24 20:03:42
【问题描述】:

我在地图上有一条自定义路线,想获取MKMapView 上两个坐标之间的距离。以下是我到目前为止所做的步骤...

  1. 我已经抓取了坐标点并准备了CLLocationCoordinate2D 的数组(比如customRoute = [CLLocationCoordinate2D])。
  2. 为了显示路线,使用坐标数组,我使用MKOverlay 方法绘制了MKPolyline
  3. 并使用distanceFromLocation方法计算两个坐标之间的距离。

当我计算距离时,得到的距离是直线距离,但不是基于方向。

假设用户位于位置 A(在自定义路线上)并且想要到达位置 B(在自定义路线上)。所以我要计算的是A和B之间的距离(不是直线距离)。

现在我正在找出距用户位置最近的坐标,并通过遍历坐标数组来计算到目的地的距离。但是当有多条路线并且最近的点在另一条路线上时,这并不能给出正确的结果。

我想到的一件事是在地图上设置自定义方向并找到距离,但我不知道如何实现这一点。

使用的语言是 Swift。

非常感谢任何形式的帮助/建议。

【问题讨论】:

    标签: ios swift mkmapview mapkit cllocationdistance


    【解决方案1】:

    According to the docs on distanceInMeters:

    此方法通过追踪来测量两个位置之间的距离 它们之间的一条线,沿着地球的曲率。这 产生的圆弧是平滑曲线,不考虑 两个位置之间的特定高度变化。

    所以该方法实际上返回了一条“直线”。

    据我所知,您需要在自定义路线的每个部分之间创建单独的 MKRoute 对象,计算这些单独的距离,然后将它们组合起来。

    正如我在this 答案中解释的那样,您可以通过获取MKDirectionsResponse 来计算每个单独的MKRoute 的距离,如下所示:

    let request:MKDirectionsRequest = MKDirectionsRequest()
    
    // source and destination are the relevant MKMapItems
    request.setSource(source)
    request.setDestination(destination)
    
    // Specify the transportation type
    request.transportType = MKDirectionsTransportType.Automobile;
    
    // If you're open to getting more than one route, 
    // requestsAlternateRoutes = true; else requestsAlternateRoutes = false;
    request.requestsAlternateRoutes = true
    
    let directions = MKDirections(request: request)
    
    directions.calculateDirectionsWithCompletionHandler ({
        (response: MKDirectionsResponse?, error: NSError?) in
    
        if error == nil {
            self.directionsResponse = response
        }
    })
    

    然后像这样得到距离:

    let route = directionsResponse.routes[currentRoute] as MKRoute
    let distance = route.distance
    

    【讨论】:

    • 不知何故,我觉得这是完成它的唯一方法。问题是我设置的路线在ios地图上没有方向,所以这是否考虑了我设置的自定义路线并根据我提供的坐标计算距离?
    • @SrujanSimha 也许我解释得不够清楚,但我认为你必须一点一点地做......就像从A点计算到B点,然后从B点计算到点C等然后将所有距离相加。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2018-10-28
    • 2016-01-03
    相关资源
    最近更新 更多