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?
Asked
Active
Viewed 241 times
-2
-
Wouldn't it be the sum of the distance between each pair of locations in your array? – rmaddy Mar 11 '19 at 23:27
-
Hint: `MKDirectionsRequest` – El Tomato Mar 11 '19 at 23:27
-
This is for when a user is on a trail so the array is custom made by the user, I don't think MKDirectionsRequest would work. Also there's the potential that the user has no cell reception...@ElTomato – Oxi Ros Mar 11 '19 at 23:45
2 Answers
2
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)

E.Coms
- 11,065
- 2
- 23
- 35
-
While this can be done in one line, its not very readable. Not everyone who sees this answer can be as clever and/or experienced as you and may get lost while trying to figure out what is what and how it all works. I think you could greatly improve your answer by providing meaningfull names and explaining what happens in each step. – Losiowaty Mar 12 '19 at 09:03
1
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

Nico S.
- 3,056
- 1
- 30
- 64