Swift中使用CoreLocation基于两坐标计算以其中一个为中心的对称坐标
计算原理
以coord1为对称中心时,根据中心对称的数学定义,coord1是coord2和coord3的中点,满足如下关系:
coord1.latitude = (coord2.latitude + coord3.latitude) / 2coord1.longitude = (coord2.longitude + coord3.longitude) / 2
转换后得到coord3的计算公式:
coord3.latitude = 2 * coord1.latitude - coord2.latitudecoord3.longitude = 2 * coord1.longitude - coord2.longitude

基础实现代码
直接基于公式计算即可,适合小范围常规场景使用:
import CoreLocation // 你的两个原始坐标 let coord1: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 30.0, longitude: 120.0) let coord2: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 31.0, longitude: 121.0) // 计算对称坐标 let coord3 = CLLocationCoordinate2D( latitude: 2 * coord1.latitude - coord2.latitude, longitude: 2 * coord1.longitude - coord2.longitude )
带边界归一化的完整实现
因为经纬度有合法范围限制(纬度:-9090,经度:-180180),计算结果超出范围时需要做归一化处理避免生成非法坐标,可以封装为扩展方便调用:
import CoreLocation extension CLLocationCoordinate2D { /// 以当前坐标为对称中心,计算目标坐标的对称坐标 /// - Parameter target: 待对称转换的目标坐标 /// - Returns: 经过边界归一化的合法对称坐标 func symmetricPoint(for target: CLLocationCoordinate2D) -> CLLocationCoordinate2D { var calculateLat = 2 * self.latitude - target.latitude var calculateLon = 2 * self.longitude - target.longitude // 纬度边界修正 calculateLat = calculateLat > 90 ? 180 - calculateLat : calculateLat calculateLat = calculateLat < -90 ? -180 - calculateLat : calculateLat // 经度边界修正 while calculateLon > 180 { calculateLon -= 360 } while calculateLon < -180 { calculateLon += 360 } return CLLocationCoordinate2D(latitude: calculateLat, longitude: calculateLon) } } // 调用示例 let coord3 = coord1.symmetricPoint(for: coord2)
注意:上述方案为平面近似计算,适用于绝大多数常规业务场景(如同城、国内范围的坐标计算),如果是跨半个地球以上的超大范围对称计算,需要额外引入地球椭球模型做精度修正。
内容的提问来源于stack exchange,提问作者Bagusflyer
相关产品推荐
相关产品推荐

