I know from documentation we can find distance between two CLLocation
points using the function, distanceFromLocation:
. But my problem is I dont ha
You should create an object of CLLocation using,
- (id)initWithLatitude:(CLLocationDegrees)latitude
longitude:(CLLocationDegrees)longitude;
Then, you should be able to calculate the distance using
[location1 distanceFromLocation:location2];
Swift4: combined above thoughts
extension CLLocationCoordinate2D {
//distance in meters, as explained in CLLoactionDistance definition
func distance(from: CLLocationCoordinate2D) -> CLLocationDistance {
let destination=CLLocation(latitude:from.latitude,longitude:from.longitude)
return CLLocation(latitude: latitude, longitude: longitude).distance(from: destination)
}
}
If it is ok for you to get distance in meters between points, then
CLLocationCoordinate2D coordinate1 = <some value>
CLLocationCoordinate2D coordinate2 = <some value>
…
MKMapPoint point1 = MKMapPointForCoordinate(coordinate1);
MKMapPoint point2 = MKMapPointForCoordinate(coordinate2);
CLLocationDistance distance = MKMetersBetweenMapPoints(point1, point2);
will return the distance between two points. No needs to create CLLocation
by given CLLocationCoordinate2D
. This defines are available since iOS 4.0
Swift 5: CLLocationCoordinate2D extension to calculate distance:
extension CLLocationCoordinate2D {
/// Returns distance from coordianate in meters.
/// - Parameter from: coordinate which will be used as end point.
/// - Returns: Returns distance in meters.
func distance(from: CLLocationCoordinate2D) -> CLLocationDistance {
let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
let to = CLLocation(latitude: self.latitude, longitude: self.longitude)
return from.distance(from: to)
}
}
Usage:
let coordinate = CLLocationCoordinate2D(latitude: 11, longitude: 39)
let from = CLLocationCoordinate2D(latitude: 30, longitude: 43)
let distance = coordinate.distance(from: from)
CLLocationDistance
is a measurement in meters.
let point1 = CLLocationCoordinate2D(latitude: lat1, longitude: lon1)
let point2 = CLLocationCoordinate2D(latitude: lat2, longitude: lon2)
let distance = point1.distance(to: point2)
let point1 = MKMapPointForCoordinate(myLocation)
let point2 = MKMapPointForCoordinate(friendLocation)
let distance = MKMetersBetweenMapPoints(point1, point2)/1000
let distanceStr = NSString(format: "%.3f", distance)
Simple version of Valleri's answer. Divide by 1000 to get KM followed by conversion to string.