You need to enable JavaScript to run this app. Swift中使用CoreLocation基于两坐标计算以其中一个为中心的对称坐标
优惠活动
大模型
产品
解决方案
定价
更多

Swift中使用CoreLocation基于两坐标计算以其中一个为中心的对称坐标

计算原理

以coord1为对称中心时,根据中心对称的数学定义,coord1是coord2和coord3的中点,满足如下关系:

coord1.latitude = (coord2.latitude + coord3.latitude) / 2
coord1.longitude = (coord2.longitude + coord3.longitude) / 2

转换后得到coord3的计算公式:

coord3.latitude = 2 * coord1.latitude - coord2.latitude
coord3.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 21:33:02