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

使用Google Distance Matrix API时返回INVALID_REQUEST错误的求助

排查并解决Google Distance Matrix API的INVALID_REQUEST错误

错误原因分析

你的请求被判定为无效,核心问题有两个:

  1. URL参数语法错误:destinations参数后缺失了必要的等号=,代码里写成了destinations${destination.description},导致API无法识别目标地址参数。
  2. URL包含多余空格与换行:模板字符串中的换行和缩进空格会被直接带入请求URL,破坏了URL的格式规范,导致API无法解析请求。

修复后的代码

const GOOGLE_API_KEY = "API_Key"

useEffect(() => {
  if (!origin || !destination) return;
  const getTravelTime = async () => {
    // 拼接规范的URL,避免多余空格换行,修正参数格式
    const url = `https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=${encodeURIComponent(origin.description)}&destinations=${encodeURIComponent(destination.description)}&key=${GOOGLE_API_KEY}`;
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      });
  };

  getTravelTime();
}, [origin, destination, GOOGLE_API_KEY]);

额外优化建议

  • 用encodeURIComponent()对地址参数编码,避免地址中的空格、逗号等特殊字符再次引发URL格式问题。
  • 确认origin.description和destination.description是有效的地址字符串,而非空值或格式错误的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:25:58