使用Google Distance Matrix API时返回INVALID_REQUEST错误的求助
排查并解决Google Distance Matrix API的INVALID_REQUEST错误
错误原因分析
你的请求被判定为无效,核心问题有两个:
- URL参数语法错误:
destinations参数后缺失了必要的等号=,代码里写成了destinations${destination.description},导致API无法识别目标地址参数。 - 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
相关产品推荐
相关产品推荐

