You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Routes API查询过路费:本地正常云端返回空问题

问题:本地可获取Google Routes API过路费,云端返回空值
  • 本地运行代码时,调用Google Routes API能正确获取过路费,响应示例:
{'routes': [{'legs': [{'travelAdvisory': {'tollInfo': {'estimatedPrice': [{'currencyCode': 'INR', 'units': '170'}]}}}], 'distanceMeters': 112558, 'duration': '7729s', 'travelAdvisory': {'tollInfo': {'estimatedPrice': [{'currencyCode': 'INR', 'units': '170'}]}}}]}}
  • 将相同代码迁移至云服务器后,过路费信息为空,云端响应示例:
{'routes': [{'legs': [{}], 'distanceMeters': 112558, 'duration': '7729s'}]}

代码完全一致,期望云端返回与本地相同的响应,参考代码如下:

import json
import requests
from your_config_module import config  # 替换为实际的配置导入方式

def FindToll(from_address,to_address):
    google_api_key = config('API_key')
                    
    url = "https://routes.googleapis.com/directions/v2:computeRoutes"

    payload = json.dumps({
        "origin": {
            "address": from_address
        },
        "destination": {
            "address": to_address
        },  
        "travelMode": "DRIVE",
        "extraComputations": ["TOLLS"],
        "routeModifiers": {
            "vehicleInfo": {
                "emissionType": "GASOLINE"
            },
            "tollPasses": [
                "IN_FASTAG"
            ]
        }
    })
    
    headers = {
        "Content-Type": "application/json",
        "X-Goog-Api-Key": google_api_key,
        "X-Goog-FieldMask":"routes.duration,routes.distanceMeters,routes.travelAdvisory.tollInfo,routes.legs.travelAdvisory.tollInfo"
    }
    
    response = requests.post(url, data=payload, headers=headers)
    res = response.json()
    
    if res.get('routes') :
        if not res.get('routes')[0].get('legs')[0]:
             return 0
        else:
             toll_cost = res.get('routes')[0].get('legs')[0].get('travelAdvisory')['tollInfo']['estimatedPrice'][0]['units']
             return int(toll_cost)
    return 0

排查方向及解决方法

  1. API密钥IP限制
    登录Google Cloud控制台,检查该API密钥的IP白名单设置。如果本地IP在允许列表但云服务器IP不在,API会限制返回过路费这类敏感数据。可以暂时移除IP限制做测试,或者将云端公网IP添加到白名单中。

  2. 请求区域头补充
    Google Routes API的过路费数据可能受请求来源区域影响,云服务器所在地区可能无法获取印度区域的过路费数据。尝试在请求头中添加区域指定:

    headers = {
        # 保留原有头部
        "X-Goog-Region": "IN"
    }
    
  3. 环境密钥一致性验证
    确认云服务器上config('API_key')加载的密钥和本地完全一致,避免因环境配置错误使用了权限不足的密钥(比如测试密钥未开通Routes API的过路费查询权限)。可以打印密钥前几位对比验证。

  4. FieldMask完整性测试
    当前的FieldMask指定了特定字段,尝试改为routes.*获取所有字段,确认是否是字段过滤导致的数据缺失:

    "X-Goog-FieldMask":"routes.*"
    

内容的提问来源于stack exchange,提问作者VTK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:46:15