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

关于使用Google Distance Matrix API获取两点间数据的代码编写咨询

看起来你已经搞定了Google Maps Distance Matrix API的请求URL构造,我来帮你补全后续的JavaScript代码实现,同时给你一些实用的避坑提示:

完整JavaScript实现(使用现代fetch API)

下面是基于你提供的请求URL,完整的异步请求代码示例,包含响应解析和错误处理:

// 假设你的坐标和API密钥已经提前定义好
const initial = [42.9814292, -70.9477546];
const destination = [51.5073509, -0.1277583];
const api_key = "YOUR_API_KEY_HERE"; // 记得替换成你的实际API密钥

// 构造请求URL(用encodeURIComponent处理参数更安全)
const requestUrl = `https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=${encodeURIComponent(initial[0] + "|" + initial[1])}&destinations=${encodeURIComponent(destination[0] + "|" + destination[1])}&key=${api_key}`;

// 发起异步请求并处理响应
fetch(requestUrl)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP请求出错!状态码:${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    // 处理API返回的距离矩阵数据
    if (data.status === "OK") {
      const routeInfo = data.rows[0].elements[0];
      console.log("两地距离:", routeInfo.distance.text);
      console.log("预计行驶时长:", routeInfo.duration.text);
      // 这里可以根据需求把数据渲染到页面或做其他业务处理
    } else {
      console.error("API请求失败:", data.status, data.error_message);
    }
  })
  .catch(error => {
    console.error("请求过程出错:", error.message);
  });
关键细节提示
  • 参数安全编码:一定要用encodeURIComponent处理坐标拼接后的字符串,避免因为特殊字符(比如意外的符号)导致请求URL失效。
  • API密钥安全:如果是前端公开代码,绝对不要直接硬编码API密钥!建议通过后端代理转发请求,防止密钥被恶意盗用。
  • 错误处理:要同时覆盖HTTP层面的错误(比如网络故障、4xx/5xx状态码)和API业务层面的错误(比如INVALID_REQUEST、OVER_QUERY_LIMIT等状态)。
  • 单位切换:你当前用的是units=imperial(英制单位,英里、英尺),如果需要公制单位,改成units=metric即可。
  • 多坐标支持:Distance Matrix API支持同时传入多个起点和终点,用|分隔即可,返回结果会是矩阵形式,你可以按需遍历处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:34:28