利用haversine方法计算两个经纬度之间的距离和方位角python代码

import math

def haversine_and_azimuth(lat1, lon1, lat2, lon2):
    def haversine(lat1, lon1, lat2, lon2):
        # 将经纬度转换为弧度
        lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])

        # haversine公式
        dlat = lat2 - lat1
        dlon = lon2 - lon1
        a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

        # 地球半径(单位:公里)
        radius = 6371.0

        # 计算距离
        distance = radius * c

        return distance

    def azimuth(lat1, lon1, lat2, lon2):
        # 将经纬度转换为弧度
        lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])

        # 计算方位角
        y = math.sin(lon2 - lon1) * math.cos(lat2)
        x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(lon2 - lon1)
        azimuth_rad = math.atan2(y, x)

        # 将弧度转换为角度
        azimuth_deg = math.degrees(azimuth_rad)

        # 调整角度范围在[0, 360)之间
        azimuth_deg = (azimuth_deg + 360) % 360

        return azimuth_deg

    # 计算距离和方位角
    distance = haversine(lat1, lon1, lat2, lon2)
    azimuth_angle = azimuth(lat1, lon1, lat2, lon2)

    return distance, azimuth_angle

# 示例用法
lat1, lon1 = 37.7749, -122.4194  # 地点1的纬度和经度(旧金山)
lat2, lon2 = 34.0522, -118.2437  # 地点2的纬度和经度(洛杉矶)

# 结果
distance, azimuth_angle = haversine_and_azimuth(lat1, lon1, lat2, lon2)

print(f"距离:{distance:.2f} 公里")
print(f"方位角:{azimuth_angle:.2f} 度")

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值