要使用Bing Maps API获取路线的距离,你需要遵循以下步骤:
curl
、requests
库等)发送GET请求到构建好的URL。下面是一个使用Python requests
库发送请求并解析响应的示例代码:
import requests
# 替换为你的Bing Maps API密钥
api_key = 'YOUR_BING_MAPS_API_KEY'
# 起点和终点的经纬度坐标
origin = '47.604,-122.332' # 示例:西雅图
destination = '47.604,-122.333' # 示例:西雅图附近的一个地点
# 构建请求URL
url = f'https://dev.virtualearth.net/REST/v1/Routes/Driving?o=xml&key={api_key}&wp.0={origin}&wp.1={destination}'
# 发送GET请求
response = requests.get(url)
# 检查响应状态码
if response.status_code == 200:
# 解析XML响应(也可以选择JSON格式)
xml_data = response.content
# 使用合适的库(如lxml或xml.etree.ElementTree)解析XML
# 这里以lxml为例
from lxml import etree
root = etree.fromstring(xml_data)
# 提取距离信息
route_distance = root.find('.//{http://schemas.microsoft.com/search/local/ws/rest/v1}Distance').text
print(f'路线距离: {route_distance}')
else:
print(f'请求失败,状态码: {response.status_code}')
请注意,你需要将YOUR_BING_MAPS_API_KEY
替换为你自己的Bing Maps API密钥。此外,根据响应格式的选择(XML或JSON),你需要使用相应的解析方法。
如果你选择JSON格式,可以使用Python的json
库来解析响应,并提取距离信息。
领取专属 10元无门槛券
手把手带您无忧上云