寻找CLLocationCoordinate2D点之间的距离
我从文档中知道我们可以使用函数distanceFromLocation:
find两个CLLocation
点之间的distanceFromLocation:
。 但我的问题是我没有CLLocation数据types与我,我有CLLocationCoordinate2D点。 那么我怎样才能find两个CLLocationCoordinate2D点之间的距离。 我看过post,但对我没有帮助。
你应该创build一个CLLocation的对象,
- (id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude;
现在使用它,你可以find距离。
如果你可以用点之间的距离来计算距离,那么
CLLocationCoordinate2D coordinate1 = <some value> CLLocationCoordinate2D coordinate2 = <some value> … MKMapPoint point1 = MKMapPointForCoordinate(coordinate1); MKMapPoint point2 = MKMapPointForCoordinate(coordinate2); CLLocationDistance distance = MKMetersBetweenMapPoints(point1, point2);
将返回两点之间的距离。 无需通过给定CLLocationCoordinate2D
创buildCLLocationCoordinate2D
。 这个定义从iOS 4.0开始可用
Swift 3:
extension CLLocation { // In meteres 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.distanceFromLocation(to) } }
let point1 = MKMapPointForCoordinate(myLocation) let point2 = MKMapPointForCoordinate(friendLocation) let distance = MKMetersBetweenMapPoints(point1, point2)/1000 let distanceStr = NSString(format: "%.3f", distance)
简单的版本Valleri的答案。 除以1000以获得KM,然后转换为string。
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) } }