3

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

 1 year ago
source link: https://www.cnblogs.com/Dast1/p/17041011.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

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

截屏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

作者:Dast1
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK