如何在客户端向Google Routes API发起请求(替代停用的Directions API)
Google Routes API 客户端调用方案
能否在客户端直接调用 Routes API?
可以,但需留意两个核心限制:
- Routes API 的 ComputeRoutes 端点支持跨域请求(Google 已配置对应 CORS 策略),但请求必须是 POST 方法并携带正确的参数格式
- 客户端直接暴露 API 密钥存在被盗用风险,适合小型内部项目或短期过渡使用,长期建议迁移至服务端代理请求
客户端调用实操步骤(JavaScript/jQuery 环境)
1. 构造请求体
Routes API 要求请求体为 JSON 格式,需包含起点、终点、出行模式等核心信息,示例如下:
const routeRequest = { origin: { address: "用户输入的起点地址" }, destination: { address: "用户输入的终点地址" }, travelMode: "DRIVE", // 可选值:DRIVE/WALK/BICYCLIST/TRANSIT routingPreference: "TRAFFIC_AWARE_OPTIMAL", languageCode: "zh-CN", units: "METRIC" };
2. 发送 POST 请求(jQuery)
直接调用 Routes API 的 ComputeRoutes 端点,需在 URL 中携带你的 API 密钥:
const API_KEY = "你的Google API密钥"; const API_URL = `https://routes.googleapis.com/directions/v2:computeRoutes?key=${API_KEY}`; $.ajax({ url: API_URL, method: "POST", contentType: "application/json", data: JSON.stringify(routeRequest), success: (res) => renderRoute(res), error: (xhr, status, err) => console.error("路线请求失败:", err) });
3. 手动渲染路线与行程详情
Routes API 没有类似 DirectionsRenderer 的客户端渲染工具,需自行解析返回数据并绘制路线:
function renderRoute(routeData) { // 假设已初始化 Google 地图实例 `map` const mainRoute = routeData.routes[0]; // 解码路线 polyline 并绘制到地图 const routeLine = new google.maps.Polyline({ path: google.maps.geometry.encoding.decodePath(mainRoute.polyline.encodedPolyline), strokeColor: "#2196F3", strokeWeight: 4, strokeOpacity: 1 }); routeLine.setMap(map); // 生成行程步骤列表 const stepsContainer = $("#trip-steps"); stepsContainer.empty(); mainRoute.legs[0].steps.forEach(step => { stepsContainer.append(`<li>${step.navigationInstruction.instruction}</li>`); }); }
关键注意事项
- 密钥安全:在 Google Cloud 控制台为 API 密钥设置域名绑定,限制仅你的项目域名可使用该密钥,降低被盗用风险
- 数据适配:Routes API 返回结构与旧版 Directions API 差异较大,需调整行程步骤、距离/时间等字段的解析逻辑
- 权限配置:确保你的 Google Cloud 项目已启用 Routes API,且密钥拥有该 API 的访问权限
内容的提问来源于stack exchange,提问作者Julius Goddard
相关产品推荐
相关产品推荐

