地图上的长度单位换算Python
时间: 2024-09-25 22:08:48 浏览: 34
在Python中进行地图上长度单位的换算,通常涉及到的是距离单位的转换,比如从公里(km)、米(m)到英里(mi),或者海里(nautical miles)等。常用的库如`geopy`可以方便地处理这类地理信息操作,包括度数到距离的转换。下面是一个简单的例子:
```python
from geopy.distance import distance
# 定义千米和英里的转换率
KILOMETERS_TO_MILES = 0.621371
METERS_TO_KILOMETERS = 1 / KILOMETERS_TO_MILES
def convert_distance(distance_in_km, to_unit):
if to_unit == 'mi':
return distance_in_km * KILOMETERS_TO_MILES
elif to_unit == 'km':
return distance_in_km
else:
raise ValueError(f"Unsupported unit: {to_unit}")
# 示例
distance_in_meters = 1000
converted_distance_to_km = convert_distance(distance_in_meters, 'km')
converted_distance_to_mi = convert_distance(distance_in_meters, 'mi')
print(f"{distance_in_meters} meters is equivalent to {converted_distance_to_km:.2f} kilometers or {converted_distance_to_mi:.2f} miles.")
阅读全文