TL;DR
let loc1 = CLLocation(latitude: lat1, longitude: lng1)
let loc2 = CLLocation(latitude: lat2, longitude: lng2)
// 计算距离
let meters: CLLocationDistance = loc1.distance(from: loc2)
其实有很多种计算距离的方法啦
- 在线 API:高德、百度
- distance = sqrt( (x1-x2)2+(y1-y2)2 )
- 球面计算距离?我数学不好
- 本地 API
既然都这么麻烦了,还是用 CoreLocation
封装好的distance
吧 ,是不是很简洁
/*
* distanceFromLocation:
*
* Discussion:
* Returns the lateral distance between two locations.
*/
@available(iOS 3.2, *)
open func distance(from location: CLLocation) -> CLLocationDistance
那这货是怎么算出来的?看下面官方的描述很靠谱啊
Returns the distance (in meters) from the receiver’s location to the specified location.
This method measures the distance between the two locations by tracing a line between them that follows the curvature of the Earth. The resulting arc is a smooth curve and does not take into account specific altitude changes between the two locations.