求助:使用Google Maps Routes API计算过路费的实现问题
解决Google Maps路线过路费计算问题
首先,你代码里的核心错误是遍历了请求对象request的steps属性——request只是你发送给API的参数,根本没有steps数据。过路费的相关信息在API返回的result对象里,而且旧的directionsService(基于Directions API v3)并不支持返回驾车路线的过路费,你需要改用新的Google Maps Routes API的Compute Routes方法,同时正确配置请求参数并解析返回结果。
步骤1:改用Routes API实现过路费计算
配置请求参数
要获取驾车过路费,请求必须包含以下关键配置:
- 指定
travelMode: "DRIVE" - 在
routeModifiers中开启tolls: true - 添加
fareOptions指定货币类型,确保API返回过路费数据 - 通过
X-Goog-FieldMask指定需要返回的字段(必须包含routes.legs.fare)
示例代码
const apiKey = "你的API密钥"; const origin = document.getElementById("from").value; const destination = document.getElementById("to").value; const requestBody = { origin: { address: origin }, destination: { address: destination }, travelMode: "DRIVE", routeModifiers: { tolls: true }, fareOptions: { currencyCode: "USD" // 按需修改货币代码,如"CNY" }, computeAlternativeRoutes: false }; fetch(`https://routes.googleapis.com/directions/v2:computeRoutes`, { method: "POST", headers: { "Content-Type": "application/json", "X-Goog-Api-Key": apiKey, "X-Goog-FieldMask": "routes.legs.fare" }, body: JSON.stringify(requestBody) }) .then(response => response.json()) .then(data => { let tollCost = 0; if (data.routes?.length > 0) { // 累加每个路段的过路费 data.routes[0].legs.forEach(leg => { if (leg.fare?.amount) { tollCost += leg.fare.amount; } }); console.log("总过路费:", tollCost); // 此处可将tollCost用于后续业务逻辑 } }) .catch(error => console.error("请求失败:", error));
步骤2:旧DirectionsService的局限性(仅作参考)
旧的directionsService.route方法仅支持公共交通(TRANSIT)模式返回fare信息,驾车模式无法获取过路费。如果只是修正遍历逻辑(无实际驾车过路费数据),写法如下:
directionsService.route(request, function (result, status) { if (status == google.maps.DirectionsStatus.OK) { let tollCost = 0; // 遍历返回结果中的路线、路段、步骤 result.routes.forEach(route => { route.legs.forEach(leg => { leg.steps.forEach(step => { // 驾车模式下该判断永远不成立 if (step.toll) { tollCost += step.toll.amount; } }); }); }); console.log(tollCost); } });
注意事项
- 确保Google Cloud账号已启用Routes API,并为API密钥配置对应权限
- 过路费数据的覆盖范围和准确性依赖Google Maps数据源,部分地区可能无法返回
- Routes API按请求次数计费,需关注计费规则
内容的提问来源于stack exchange,提问作者Rafax
相关产品推荐
相关产品推荐

