> 技术文档 > python调用高德API查询两点间的路线规划_python调用高德api路径规划

python调用高德API查询两点间的路线规划_python调用高德api路径规划

采用的是python+Flask

功能说明

输入设置:

在起点/终点输入框中输入位置

选择出行方式(步行/骑行/驾车)

路线规划:

点击\"规划路线\"按钮获取路线

地图显示规划路线(蓝色线条)

显示起点(绿色)和终点(红色)标记

右侧显示路线距离和预计时间

交互功能:

地图支持缩放、拖动

可切换不同出行方式重新规划

整体实现效果如图:

python调用高德API查询两点间的路线规划_python调用高德api路径规划

文件结构:

/project-root
├── app.py # Flask主程序
├── config.py # 配置文件
├── templates
│ └── index.html # 前端页面
└── static
└── style.css # 样式文件

  1. 配置文件 (config.py)
# 填入从高德地图获取的API KeyAMAP_WEB_API_KEY = \'你的Web服务API Key\' # 用于后端API调用AMAP_JS_API_KEY = \'你的JavaScript API Key\' # 用于前端地图显示
  1. Flask主程序 (app.py)
from flask import Flask, render_template, request, jsonifyimport requestsimport configapp = Flask(__name__)# 高德API端点AMAP_GEOCODE_API = \"https://restapi.amap.com/v3/geocode/geo\"AMAP_ROUTE_API = {  \"walking\": \"https://restapi.amap.com/v3/direction/walking\", \"driving\": \"https://restapi.amap.com/v3/direction/driving\", \"bicycling\": \"https://restapi.amap.com/v4/direction/bicycling\"}# 出行方式映射MODE_MAPPING = {  \"walking\": \"walking\", \"bicycling\": \"bicycling\", \"driving\": \"driving\"}def geocode_address(address): \"\"\"将地址转换为坐标\"\"\" params = {  \"key\": config.AMAP_WEB_API_KEY, \"address\": address, \"output\": \"JSON\" } response = requests.get(AMAP_GEOCODE_API, params=params) result = response.json() print(f\"地理编码响应: { result}\") # 调试日志 if result.get(\"status\") == \"1\" and result.get(\"geocodes\"): location = result[\"geocodes\"][0][\"location\"] return location return None@app.route(\'/\')def index(): return render_template(\'index.html\', js_api_key=config.AMAP_JS_API_KEY)@app.route(\'/get_route\', methods=[\'POST\'])def get_route(): data = request.json start_address = data[\'start\'] end_address = data[\'end\'] mode = MODE_MAPPING.get(data[\'mode\'], \'walking\') # 地理编码:将地址转换为坐标 start_location = geocode_address(start_address) end_location = geocode_address(end_address) print(f\"起点坐标: { start_location}, 终点坐标: { end_location}\") # 调试日志 if not start_location or not end_location: return jsonify({  \"status\": \"error\", \"message\": \"地址解析失败,请检查输入\" }) # 构建请求参数 params = {  \"key\": config.AMAP_WEB_API_KEY, \"origin\": start_location, \"destination\": end_location } try: # 获取对应模式的API URL url = AMAP_ROUTE_API[mode] print(f\"请求URL: { url}\") print(f\"请求参数: { params}\") response = requests.get(url, params=params) result = response.json() print(f\"高德API响应: { result}\") # 调试日志 # 处理骑行API的响应 if mode == \"bicycling\": if result.get(\"errcode\") == 0 and result.get(\"data\", { }).get(\"paths\"): path_info = result[\"data\"][\"paths\"][0] # 解析坐标点 - 骑行数据包含多个steps,每个step有polyline points = [] for step in path_info[\"steps\"]:  if \"polyline\" in step and step[\"polyline\"]: polyline = step[\"polyline\"].split(\";\") for point in polylin