【问题标题】:Count distance on polyline swift快速计算折线上的距离
【发布时间】:2019-08-02 20:10:12
【问题描述】:

我创建了一张地图,您可以在其中按下开始按钮。然后应用程序将放大到您的当前位置,并每 10 秒更新一次坐标并插入到坐标数组中。一旦我按下停止按钮,我就有一条折线在所有坐标之间画线。 (如下图)

所以我现在的问题是: 如何计算折线的绘制距离?

//Draw polyline on the map
let aPolyLine = MKPolyline(coordinates: self.locations, count: self.locations.count)

    //Adding polyline to mapview
    self.mapView.addOverlay(aPolyLine)

    let startResult = self.locations.startIndex
    let stopResult = self.locations.endIndex

    //Retrieve distance and convert into kilometers
    let distance = startResult.distance(to: stopResult)
    let result = Double(distance) / 1000
    let y = Double(round(10 * result)) / 10
    self.KiloMeters.text = String(y) + " km"

我的猜测是我不能使用 startResult.distnace(to: stopResult) 因为,如果我绕一圈,公里会显示 0?正确的?我不确定,但它仍然有效。像我一样使用代码时没有显示任何内容。

【问题讨论】:

  • 添加每个点到下一个点的距离
  • 你有一个位置数组。遍历数组,找到每个点与下一个点之间的距离。总这些距离
  • CLLocation 类中有一个distance(from:) 方法
  • 不确定 distance(to:) 是什么,但如果它适合你,那么就使用它,否则就像我说的另一个函数在 CLLocation 类中。
  • @Putte,你使用的这个distance(to:)实际上是Array.Index类型的方法,现在是IntAnd this function just returns difference between two indexes。对于Array 中的.startIndex.endIndex,它只是数组的长度。

标签: ios swift polyline mkpolyline


【解决方案1】:
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
    // MARK: - Variables
    let locationManager = CLLocationManager()

    // MARK: - IBOutlet
    @IBOutlet weak var mapView: MKMapView!

    // MARK: - IBAction
    @IBAction func distanceTapped(_ sender: UIBarButtonItem) {
        let locations: [CLLocationCoordinate2D] = [...]
        var total: Double = 0.0
        for i in 0..<locations.count - 1 {
            let start = locations[i]
            let end = locations[i + 1]
            let distance = getDistance(from: start, to: end)
            total += distance
        }
        print(total)
    }

    func getDistance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
        // By Aviel Gross
        // https://stackoverflow.com/questions/11077425/finding-distance-between-cllocationcoordinate2d-points
        let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
        let to = CLLocation(latitude: to.latitude, longitude: to.longitude)
        return from.distance(from: to)
    }
}

【讨论】:

  • 我可以在播放按钮中添加该代码而不是“distanceTapped”吗?让它自动?非常感谢您的意见,我会调查这个
  • 是的。不过,根据您的代码,您必须为自己提供位置,一个 CLLocationCoordinate2D 数组。
  • 似乎工作正常!现在的结果是:4.5668457328325329。 (它是 4 米)。如何删除“.5668457328325329”?你知道吗?我试过 /1000 等,但没有真正正常工作
  • @Putte,您确定要将其四舍五入吗?因为它更接近5 而不是4
猜你喜欢
  • 1970-01-01
  • 2016-05-19
  • 2019-09-25
  • 2015-10-29
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
  • 2017-08-10
  • 2019-07-30
相关资源
最近更新 更多