方法一
参考:Moving a CLLocation by x meters
使用 Haversine Formula,公式考虑了地球的曲率,能够精确计算两个点之间的距离。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| func calculateDistance(from coord1: CLLocationCoordinate2D, to coord2: CLLocationCoordinate2D) -> Double {
let earthRadius: Double = 6372797.6 let lat1 = coord1.latitude * .pi / 180 let lat2 = coord2.latitude * .pi / 180 let deltaLat = (coord2.latitude - coord1.latitude) * .pi / 180 let deltaLon = (coord2.longitude - coord1.longitude) * .pi / 180 let a = sin(deltaLat / 2) * sin(deltaLat / 2) + cos(lat1) * cos(lat2) * sin(deltaLon / 2) * sin(deltaLon / 2) let c = 2 * atan2(sqrt(a), sqrt(1 - a)) return earthRadius * c }
|
方法二
将经纬度转换成墨卡托投影坐标,然后通过 MKMapPoint.distance
计算两点的距离。
1 2 3 4 5 6 7
| let coordinate1 = CLLocationCoordinate2D(latitude: 28.209321, longitude: 112.843033) let coordinate2 = CLLocationCoordinate2D(latitude: 28.209321, longitude: 112.843033)
let point1: MKMapPoint = MKMapPoint(Coordinate1) let point2: MKMapPoint = MKMapPoint(Coordinate2)
let distance = point1.distance(to: point2)
|
已知方向与距离,计算目标点的坐标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import Foundation
func calculateNewLocation(startLatitude: Double, startLongitude: Double, distanceInMeters: Double, bearingInDegrees: Double) -> (latitude: Double, longitude: Double) {
let radiusOfEarth = 6378137.0
let bearingRadians = bearingInDegrees * Double.pi / 180.0
let newLatitude = startLatitude + (distanceInMeters * cos(bearingRadians)) / (radiusOfEarth * Double.pi / 180.0) let newLongitude = startLongitude + (distanceInMeters * sin(bearingRadians)) / (radiusOfEarth * Double.pi / 180.0 * cos(startLatitude * Double.pi / 180.0))
return (latitude: newLatitude, longitude: newLongitude) }
let startLat = 22.302711 let startLon = 114.177216 let distance = 100.0 let bearing = 45.0
let newLocation = calculateNewLocation(startLatitude: startLat, startLongitude: startLon, distanceInMeters: distance, bearingInDegrees: bearing)
print("起始点: 纬度: \(startLat), 经度: \(startLon)") print("新点: 纬度: \(newLocation.latitude), 经度: \(newLocation.longitude)")
|