from geopy.distance import geodesic
import math
def calculate_heading(start_coords, end_coords):
"""
计算从起始坐标到结束坐标的初始航向。
:param start_coords: 起始点的经纬度 (纬度, 经度),单位为度数
:param end_coords: 结束点的经纬度 (纬度, 经度),单位为度数
:return: 初始航向,单位为度数,范围在0-360之间
"""
# 将经纬度从度数转换为弧度
lat1, lon1 = math.radians(start_coords[0]), math.radians(start_coords[1])
lat2, lon2 = math.radians(end_coords[0]), math.radians(end_coords[1])
# 计算差值
dLon = lon2 - lon1
# 使用Haversine公式的一部分来计算初始方位角(航向)
x = math.sin(dLon) * math.cos(lat2)
y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1) * math.cos(lat2) * math.cos(dLon))
# 计算方位角(结果可能在-π到π之间)
initial_bearing = math.atan2(x, y)
# 将方位角从弧度转换为度数
initial_bearing_degrees = math.degrees(initial_bearing)
# 将方位角调整到0-360度范围内
initial_bearing_degrees = (initial_bearing_degrees + 360) % 360
return initial_bearing_degrees
def calculate_heading_and_distance(start_coords, end_coords):
"""
计算从起始坐标到结束坐标的距离和初始航向。
:param start_coords: 起始点的经纬度 (纬度, 经度),单位为度数
:param end_coords: 结束点的经纬度 (纬度, 经度),单位为度数
:return: 一个元组,包含距离(米)和初始航向(度数)
"""
# 使用geopy库中的geodesic函数计算两点之间的距离
distance = geodesic(start_coords, end_coords).meters
# 计算初始航向
heading = calculate_heading(start_coords, end_coords)
return distance, heading
# 示例使用:计算从北京市到上海市的距离和航向
a_coords = (39.9042, 116.4074) # 北京市的经纬度
b_coords = (31.2304, 121.4737) # 上海市的经纬度
# 调用函数并打印结果
distance, heading = calculate_heading_and_distance(a_coords, b_coords)
print(f"Distance from A (Beijing) to B (Shanghai): {distance:.2f} meters")
print(f"Heading from A (Beijing) to B (Shanghai): {heading:.2f} degrees")