iOS根据两点经纬度坐标计算指南针方位角

发布时间 2023-03-22 19:09:17作者: Dast1

需求

在地图导航时,始终保持当前路段竖直超前。

设计

因地图暴露的方法中只有设置地图相对于正北的方向角的方法。因此,需要实现“根据两点经纬度坐标计算指南针方位角”的算法,这样在每次切换路段时,调用算法计算新路段指南针方位角,然后设置地图相对于正北的方向角即可实现需求。
示意图如下:
截屏2023-01-10 15.57.34

算法实现原理详见文末引用。下面贴出基于 OC 语言的代码实现。

代码实现

新建CLLocation 分类方法

#import <CoreLocation/CoreLocation.h>

+ (double)ca_getCompassAngleFromCoor1:(CLLocationCoordinate2D)coor1 coor2:(CLLocationCoordinate2D)coor2 {
    double long1 = coor1.longitude;
    double lat1 = coor1.latitude;
    double long2 = coor2.longitude;
    double lat2 = coor2.latitude;
         
    double φ1 = [CLLocation toRadius:lat1];
    double φ2 = [CLLocation toRadius:lat2];
    double Δλ = [CLLocation toRadius:(long2 - long1)];
    
    double x = cos(φ1) * sin(φ2) - sin(φ1) * cos(φ2) * cos(Δλ);
    double y = sin(Δλ) * cos(φ2);
    double θ = atan2(y, x);
    
    double bearing = [CLLocation toDegrees:θ];
    return bearing;
}

+ (double)toDegrees:(double)radius {
    return radius * 180.0 / M_PI;
}

+ (double)toRadius:(double)degree {
    return degree * M_PI / 180.0;
}

调用示例

double bearing = [CLLocation ca_getCompassAngleFromCoor1:(CLLocationCoordinate2DMake(20, 20)) coor2:(CLLocationCoordinate2DMake(20, 140))];
NSLog(@"bearing:%.2f", bearing);
//设置地图方位角...

结论

经测试,上面算法可以满足需求,且效果正确!

https://www.movable-type.co.uk/scripts/latlong.html