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

求Node.js中@googlemaps/google-maps-services-js的Distance Matrix API调用示例

使用@googlemaps/google-maps-services-js调用Google Maps Distance Matrix API示例

以下是完整的Node.js环境下调用Google Maps Distance Matrix API的代码示例,基于@googlemaps/google-maps-services-js库:

const { Client } = require("@googlemaps/google-maps-services-js");

const client = new Client({});

client
  .distanceMatrix({
    params: {
      // 起点,支持单个/多个坐标对象或地址字符串
      origins: [{ lat: 37.7749, lng: -122.4194 }], // 示例:旧金山坐标
      // 终点,支持单个/多个坐标对象或地址字符串
      destinations: [{ lat: 34.0522, lng: -118.2437 }], // 示例:洛杉矶坐标
      // 替换为你的Google Maps API密钥
      key: "YOUR_GOOGLE_MAPS_API_KEY",
      // 可选:出行模式,默认driving,可选transit/walking/bicycling
      mode: "driving",
      // 可选:单位,默认metric(公里/米),可选imperial(英里/英尺)
      units: "metric"
    },
    timeout: 5000 // 请求超时时间,单位毫秒
  })
  .then((response) => {
    // 解析返回结果
    const element = response.data.rows[0].elements[0];
    if (element.status === "OK") {
      console.log(`距离:${element.distance.text}`);
      console.log(`预计时长:${element.duration.text}`);
      // 获取数值格式的距离(米)和时长(秒)
      console.log(`距离(米):${element.distance.value}`);
      console.log(`预计时长(秒):${element.duration.value}`);
    } else {
      console.log(`结果状态异常:${element.status}`);
    }
  })
  .catch((error) => {
    // 处理请求错误
    console.error(`请求失败:${error.response?.data?.error_message || error.message}`);
  });

关键说明:

  • 库的标准方法名为distanceMatrix,并非你写的distanceMatrixrequest。
  • origins和destinations支持多种输入格式:比如直接传地址字符串"San Francisco, CA",或多个坐标/地址组成的数组。
  • 需确保API密钥已在Google Cloud控制台启用Distance Matrix API权限,否则会返回权限错误。
  • 可根据需求添加额外参数,比如departure_time(获取实时交通时长)、avoid(避开高速/收费站等)。

内容的提问来源于stack exchange,提问作者Abdallah Mushi Nourdin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:55:35