我已经创建了一个地图,您可以按下开始按钮。然后,应用程序将放大到您当前的位置,并每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
// 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)
}
}