python从谷歌地图获取经纬度坐标之间的导航信息
使用谷歌地图获取经纬度坐标之间的导航信息
import googlemaps
import re
def remove_html_tags(html_string):
# 使用正则表达式去除 HTML 标签
clean_text = re.sub(r'<[^>]+>', '', html_string)
return clean_text
def feet_to_meters(feet):
# 将英尺转为米
feet = float(feet.split(' ')[0])
meters = feet * 0.3048
meters = f"{meters:.2f} m"
return meters
# 你的Google Maps API密钥
api_key = YOUR_API_KEY
gmaps = googlemaps.Client(key=api_key)
# 起点和终点的经纬度坐标
origin = (42.351648599736414, -71.05055898203881) # 旧金山
destination = (42.350981509346674, -71.04944889831783) # 洛杉矶
# 请求导航指令
directions_result = gmaps.directions(origin, destination, mode="driving", departure_time="now")
# 打印详细的导航指令
for route in directions_result:
for leg in route['legs']:
for step in leg['steps']:
# 打印每一步的指令
print(f"Navigation: {remove_html_tags(step['html_instructions'])}")
# 打印每一步的距离和时间
print(f"Distance: {feet_to_meters(step['distance']['text'])}")
print(f"Duration: {step['duration']['text']}")
# 打印每一步的转弯图示(可选)
if 'travel_mode' in step:
print(f"Travel Mode: {step['travel_mode']}")
# 打印每一步的交通方式(可选)
if 'maneuver' in step:
print(f"Maneuver: {step['maneuver']}")