How can I calculate the total distance traveled use CoreLocation in Swift
I haven't been able to so far find any resources for how to do this in Swift for iOS 8,
How would you calculate the total distance moved since you began tracking your location?
From what I've read so far, I need to save location of a points, then calculate the distance between current point, and last point, then add that distance to a totalDistance variable
Objective-C is extremely unfamiliar to me, so I haven't been able to work out the swift syntax
Here is what I've worked out so far, not sure if I'm doing it right. Though the distanceFromLocation
method is returning all 0.0 so obviously something is wrong
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var newLocation: CLLocation = locations[0] as CLLocation
oldLocationArray.append(newLocation)
var totalDistance = CLLocationDistance()
var oldLocation = oldLocationArray.last
var distanceTraveled = newLocation.distanceFromLocation(oldLocation)
totalDistance += distanceTraveled
println(distanceTraveled)
}
Leo Dabus method could be used to calculate the geographical distance between your actual location and start one.
In order to obtain the precise traveled distance, you have to update "traveledDistance" using the difference between the last position and the old one.
This is my implementation:
If you want to calculate the route distance between two points you need to use
MKDirectionsRequest
, this will return you one, or many, routes from point A to point B with the step by step instruction:This example code will return you this:
The function can be easily modified to receive two locations and return the distance and any other needed information.
I hope that helps you!
update: Xcode 8.3.2 • Swift 3.1
The problem there is because you are always getting the same location over and over again. Try like this:
Sample Project