Node.js+Express调用Google Maps API无法获取路线数据求助
解决Google Maps Directions API调用失败问题
以下是针对你代码问题的排查和修复步骤:
检查API密钥配置
- 确保你已经将
"myGoogleApiKey"替换为真实有效的Google Cloud API密钥 - 登录Google Cloud控制台,确认该密钥已启用Directions API,且没有触发配额限制或IP访问限制
- Google Maps API服务需要绑定有效计费账号(即使在免费额度内),确认你的账号已完成计费设置
- 确保你已经将
延长请求超时时间
当前设置的timeout: 1000(1秒)过短,API响应可能无法在该时间内返回,导致超时失败。将超时时间调整为5秒或更长:const directionsResponse = await googleMapsClient.directions({ params: { origin: fromLocation, destination: toLocation, mode: 'walking' }, timeout: 5000, // 调整为5秒超时 });优化错误日志定位问题
原代码的错误日志仅打印error.response.data,若遇到无响应的错误(如网络超时)会导致额外报错。修改catch块打印完整错误信息,方便精准定位:catch (error) { console.error('完整错误信息:', error); if (error?.response) { console.error('API返回错误:', error.response.data); } res.status(500).json({ error: 'Failed to calculate route', errorDetails: error.message }); }验证请求参数合理性
Galle到Ella的距离约190公里,步行模式下Google Maps可能无法生成有效路线。建议先切换为mode: 'driving'测试API是否能正常返回数据,确认服务正常后再尝试步行模式(若实际场景确实需要长距离步行路线,可能需要拆分路段或调整参数)
修改后的完整代码示例
const express = require('express'); const app = express(); const { Client } = require('@googlemaps/google-maps-services-js'); // 替换为你的真实API密钥 const googleMapsClient = new Client({apiKey:"YOUR_REAL_GOOGLE_API_KEY"}); app.use(express.json()); app.get('/calculate-route', async (req, res) => { const fromLocation = "Galle, Sri Lanka"; const toLocation = "Ella, Sri Lanka"; try { const directionsResponse = await googleMapsClient.directions({ params: { origin: fromLocation, destination: toLocation, mode: 'driving' // 先测试驾车模式 }, timeout: 5000, }); res.json(directionsResponse.data); } catch (error) { console.error('完整错误信息:', error); if (error?.response) { console.error('API返回错误:', error.response.data); } res.status(500).json({ error: 'Failed to calculate route', errorDetails: error.message }); } }); const PORT = process.env.PORT || 3001; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
内容的提问来源于stack exchange,提问作者Ashfaq Farleen
相关产品推荐
相关产品推荐

