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

Node.js中如何获取Google Maps两地间分钟级旅行时长?

解决google-distance库返回duration.value为undefined的问题

嘿,我之前也碰到过一模一样的情况!大概率是两个核心问题:要么你没配置Google Maps的API密钥(现在Google的距离服务几乎都需要密钥才能返回完整数据),要么这个老库的响应结构已经跟不上Google API的更新了。咱们一步步来解决:

第一步:先排查API密钥的问题

很多人容易忽略,现在Google Distance Matrix API是需要在Google Cloud平台申请密钥,并且启用对应的API服务才能正常使用的。你用的google-distance库是封装了这个API,如果没传密钥,API可能只返回基础信息,甚至直接缺失duration这类关键字段,导致你拿到undefined。

试试修改代码加上密钥:

var distance = require('google-distance');
distance.apiKey = '你的Google Maps API密钥'; // 替换成你自己的密钥

distance.get({ 
  origin: 'San Francisco, CA', 
  destination: 'San Diego, CA',
  mode: 'driving' // 可选,指定出行模式:driving/walking/bicycling/transit
}, function(err, data) {
  if (err) { 
    return console.log(err); 
  } else {
    // 先打印完整响应,看看实际返回的结构是什么样的
    console.log('完整响应数据:', data); 
    if (data.duration && data.duration.value) {
      const travelMinutes = Math.floor(data.duration.value / 60);
      console.log('旅行时长(分钟):', travelMinutes);
    } else {
      console.log('没找到duration.value字段,大概率是密钥或API权限问题');
    }
  }
});

第二步:如果还是不行,换用官方维护的库

google-distance这个库最后一次更新是2017年,太老了,Google Maps API的响应结构这些年已经有变化,导致这个库解析出来的数据可能和你预期的不一样。建议换成Google官方维护的@googlemaps/google-maps-services-js,稳定性和兼容性都好太多。

改用官方库的步骤:

  1. 先安装库:
npm install @googlemaps/google-maps-services-js
  1. 编写测试代码:
const { Client } = require('@googlemaps/google-maps-services-js');
const client = new Client({});

client.distancematrix({
  params: {
    origins: ['San Francisco, CA'],
    destinations: ['San Diego, CA'],
    key: '你的Google Maps API密钥'
  },
  timeout: 10000 // 设置10秒超时,避免请求挂起
}).then(response => {
  // 按照Google官方API的结构解析数据
  const durationSeconds = response.data.rows[0].elements[0].duration.value;
  const travelMinutes = Math.floor(durationSeconds / 60);
  console.log('旅行时长(分钟):', travelMinutes);
}).catch(err => {
  console.log('请求出错:', err.response ? err.response.data : err.message);
});

最后再确认两个关键点

  • 确保你的Google Cloud账号已经启用了Distance Matrix API,并且密钥没有设置IP限制或者权限不足的问题。
  • 如果还是有疑问,直接用Postman或者curl调用Google的Distance Matrix API接口,看看原始返回数据里有没有duration字段,这样就能快速定位是库的问题还是API配置的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 02:22:41