I have 2 CLLocation coordinates and I wanna know the distance between them using as a path an array of coordinates that go from point A to B. I know how to calculate the distance from point A to B but the problem is that it seems to be measured in a straight line rather than following a given route. Any idea on how to do this efficiently?
It's very simple if you have all CLLocations. Just one line code can do it. For example:
var locations : [CLLocation] = [CLLocation.init(latitude: CLLocationDegrees(10.00000), longitude: CLLocationDegrees(100.00000)),
CLLocation.init(latitude: CLLocationDegrees(10.00001), longitude: CLLocationDegrees(100.00001)),
CLLocation.init(latitude: CLLocationDegrees(10.00002), longitude: CLLocationDegrees(100.00002)),
CLLocation.init(latitude: CLLocationDegrees(10.00003), longitude: CLLocationDegrees(100.00003)),
]
let totalDistance = locations.dropFirst().reduce((locations.first!, 0.0)) { ($1 , $0.1 + $0.0.distance(from: $1)) }.1
print(totalDistance)
I made E.Coms answer more readable:
guard let firstLocation = locations.first else { return }
let distance = locations.reduce((location: firstLocation, distance: 0.0)) { partialResult, nextLocation in
return (nextLocation, partialResult.distance + partialResult.location.distance(from: nextLocation))
}.distance
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.