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

如何通过Google Maps JavaScript Directions Service获取路径各点间时长?

解决Google Maps Directions Service中Step内部路径点间时长获取问题

Google Maps Directions Service的官方响应确实不会提供Step内部路径点(path里的LatLng对象)之间的细分时长——这些点是道路的几何采样节点,并非导航的关键步骤,所以API只返回整个Step的总时长和总距离。下面提供两种可行的解决思路:

方法一:基于距离比例估算时长

这种方法通过计算Step内相邻路径点的距离占比,来拆分Step的总时长,属于近似估算,适合对精度要求不是极高的场景。

实现步骤:

  1. 遍历目标Step的path数组,计算每一对相邻点的直线距离
  2. 累加所有相邻点的距离,得到该Step的总路径长度
  3. 用每个小段的距离除以总长度,得到占比,再乘以Step的总时长,得到该小段的估算时长

代码示例:

// 假设已获取到目标Step对象:step
const pathPoints = step.path;
const stepTotalDuration = step.duration.value; // 总时长(单位:秒)
let totalPathDistance = 0;
const segmentDurations = [];

// 先计算Step内路径的总长度
for (let i = 0; i < pathPoints.length - 1; i++) {
  const segmentDistance = google.maps.geometry.spherical.computeDistanceBetween(
    pathPoints[i],
    pathPoints[i + 1]
  );
  totalPathDistance += segmentDistance;
}

// 拆分计算每个路段的估算时长
for (let i = 0; i < pathPoints.length - 1; i++) {
  const segmentDistance = google.maps.geometry.spherical.computeDistanceBetween(
    pathPoints[i],
    pathPoints[i + 1]
  );
  const segmentDuration = (segmentDistance / totalPathDistance) * stepTotalDuration;
  segmentDurations.push({
    from: pathPoints[i],
    to: pathPoints[i + 1],
    duration: {
      value: Math.round(segmentDuration),
      text: google.maps.convertDurationToString(Math.round(segmentDuration))
    }
  });
}

方法二:调用Distance Matrix API精准计算

如果需要高精度的时长数据,可以对每一对相邻路径点调用Google Maps Distance Matrix API,直接获取两点间的导航时长。但要注意,这种方法会增加API调用次数,需考虑配额限制和成本。

实现步骤:

  1. 遍历Step的path数组,生成相邻点的坐标对
  2. 批量或逐个调用Distance Matrix API,请求每对坐标的对应出行方式时长
  3. 解析响应,提取每段的时长数据

代码示例:

// 假设已获取到目标Step对象:step
const pathPoints = step.path;
const segmentDurations = [];

// 遍历相邻点对,调用API获取时长
for (let i = 0; i < pathPoints.length - 1; i++) {
  const origin = `${pathPoints[i].lat()},${pathPoints[i].lng()}`;
  const destination = `${pathPoints[i + 1].lat()},${pathPoints[i + 1].lng()}`;

  const service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix({
    origins: [origin],
    destinations: [destination],
    travelMode: google.maps.TravelMode.DRIVING, // 需匹配原Directions请求的出行方式
    unitSystem: google.maps.UnitSystem.METRIC
  }, (response, status) => {
    if (status === google.maps.DistanceMatrixStatus.OK) {
      const duration = response.rows[0].elements[0].duration;
      segmentDurations.push({
        from: pathPoints[i],
        to: pathPoints[i + 1],
        duration: duration
      });
    } else {
      console.error(`获取路段时长失败:${status}`);
    }
  });
}

注意事项:

  • 若path点数量较多,建议批量请求(Distance Matrix支持多组origins和destinations),减少API调用次数
  • 需确保API密钥拥有Distance Matrix API的访问权限,同时注意请求频率和配额限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:10:55