我从文档中了解到,我们可以使用函数CLLocation
找到两个distanceFromLocation:
点之间的距离。但我的问题是我没有CLLocation数据类型与我,我有CLLocationCoordinate2D点。那么如何找到两个CLLocationCoordinate2D点之间的距离。我看过帖子post但对我没用。
答案 0 :(得分:34)
您应该使用
创建CLLocation对象- (id)initWithLatitude:(CLLocationDegrees)latitude
longitude:(CLLocationDegrees)longitude;
然后,您应该能够使用
计算距离[location1 distanceFromLocation:location2];
答案 1 :(得分:27)
如果您可以在两点之间获得距离,那么
CLLocationCoordinate2D coordinate1 = <some value>
CLLocationCoordinate2D coordinate2 = <some value>
…
MKMapPoint point1 = MKMapPointForCoordinate(coordinate1);
MKMapPoint point2 = MKMapPointForCoordinate(coordinate2);
CLLocationDistance distance = MKMetersBetweenMapPoints(point1, point2);
将返回两点之间的距离。无需按给定CLLocation
创建CLLocationCoordinate2D
。此定义自iOS 4.0起可用
答案 2 :(得分:25)
Swift 4:
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(to)
}
}
答案 3 :(得分:16)
Swift4:结合以上思路
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)
}
}
答案 4 :(得分:5)
let point1 = MKMapPointForCoordinate(myLocation)
let point2 = MKMapPointForCoordinate(friendLocation)
let distance = MKMetersBetweenMapPoints(point1, point2)/1000
let distanceStr = NSString(format: "%.3f", distance)
简单版的Valleri的回答。除以1000得到KM,然后转换为字符串。
答案 5 :(得分:1)
Swift 5 :用于计算距离的CLLocationCoordinate2D扩展名:
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)
}
}
用法:
let coordinate = CLLocationCoordinate2D(latitude: 11, longitude: 39)
let from = CLLocationCoordinate2D(latitude: 30, longitude: 43)
let distance = coordinate.distance(from: from)
答案 6 :(得分:0)
MKMetersBetweenMapPoints
现在只是MKMapPoint
let coordinate1 = CLLocationCoordinate2D(latitude: lat1, longitude: lon1)
let coordinate2 = CLLocationCoordinate2D(latitude: lat2, longitude: lon2)
let point1 = MKMapPoint(coordinate1)
let point2 = MKMapPoint(coordinate2)
let distance = point1.distance(to: point2)