Finding distance between CLLocationCoordinate2D points
I know from documentation we can find distance between two CLLocation
points using the function, distanceFromLocation:
. But my problem is I dont have CLLocation data type with me, I have the CLLocationCoordinate2D points. So how can I find distance between two CLLocationCoordinate2D points. I have seen the post post but not helpful for me.
Solution 1:
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];
Solution 2:
Swift 5:
extension CLLocation {
/// Get distance between two points
///
/// - Parameters:
/// - from: first point
/// - to: second point
/// - Returns: the distance in meters
class func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
let to = CLLocation(latitude: to.latitude, longitude: to.longitude)
return from.distance(from: to)
}
}
Solution 3:
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
Solution 4:
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)
}
}