[python]输入位置的坐标,计算两点的距离结果并保留两位

from geopy.distance import geodesic

def calculate_distance(lat1, lon1, lat2, lon2):
    # 创建两个位置的坐标对象
    loc1 = (lat1, lon1)
    loc2 = (lat2, lon2)

    # 使用geodesic函数计算两点之间的距离
    distance = geodesic(loc1, loc2).kilometers

    # 将距离保留两位小数
    distance_rounded = round(distance, 2)

    return distance_rounded

# 举例:北京 (39.9042° N, 116.4074° E) 和上海 (31.2304° N, 121.4737° E)
lat1 = 39.9042
lon1 = 116.4074
lat2 = 31.2304
lon2 = 121.4737

distance = calculate_distance(lat1, lon1, lat2, lon2)
print(f"The distance between the two points is {distance} kilometers.")
 

你可能感兴趣的:(python)