计算折线上的距离 swift

Count distance on polyline swift

我创建了一个地图,您可以在其中按开始按钮。然后应用程序将放大到您当前的位置,并每 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?正确的?我不确定,但它仍然有效。像我一样使用代码时没有任何显示。

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
        // 
        let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
        let to = CLLocation(latitude: to.latitude, longitude: to.longitude)
        return from.distance(from: to)
    }
}