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

科技资讯 投稿 5700 0 评论

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

需求

设计

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

代码实现

新建CLLocation 分类方法

#import <CoreLocation/CoreLocation.h>

+ (doubleca_getCompassAngleFromCoor1:(CLLocationCoordinate2Dcoor1 coor2:(CLLocationCoordinate2Dcoor2 {
    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;
}

+ (doubletoDegrees:(doubleradius {
    return radius * 180.0 / M_PI;
}

+ (doubletoRadius:(doubledegree {
    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

编程笔记 » iOS根据两点经纬度坐标计算指南针方位角

赞同 (31) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽