Swift 计算地图上两点的物理距离

方法一

参考: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

// Haversine公式
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 // 示例距离,100米
let bearing = 45.0 // 示例方向,45度 (东北方向)

let newLocation = calculateNewLocation(startLatitude: startLat, startLongitude: startLon, distanceInMeters: distance, bearingInDegrees: bearing)

print("起始点: 纬度: \(startLat), 经度: \(startLon)")
print("新点: 纬度: \(newLocation.latitude), 经度: \(newLocation.longitude)")

Swift 计算地图上两点的物理距离
https://wonderhoi.com/2025/01/11/Swift-计算地图上两点的物理距离/
作者
wonderhoi
发布于
2025年1月11日
许可协议