distanceFromLocation - Calculate distance between two points
In Swift
Let's create a method function that calculates distance between two locations:
func distanceBetweenTwoLocations(source:CLLocation,destination:CLLocation) -> Double{
var distanceMeters = source.distanceFromLocation(destination)
var distanceKM = distanceMeters / 1000
let roundedTwoDigit = distanceKM.roundedTwoDigit
return roundedTwoDigit
}
If you want only two digits:
extension Double{
var roundedTwoDigit:Double{
return Double(round(100*self)/100)
}
}
The distance is calculated between 2 CLLocations and not between to coordinates.
You need to use these coordinates to get the CLLocations for the respective coordinates using the following line of code
CLLocation *newLocation = [[CLLocation alloc] initWithCoordinate: newCoordinate altitude:1 horizontalAccuracy:1 verticalAccuracy:-1 timestamp:nil];
Similarly for the other coordinate and then you can calculate the distance between these two locations using the following line of code
CLLocationDistance kilometers = [newLocation distanceFromLocation:oldLocation] / 1000;
Hope this will help you.
Update: Swift 3.0
let distanceKiloMeters = (newLocation.distance(from: oldLocation))/1000
Try this instead:
CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
The method you're trying to use is a method on a CLLocation object :)