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

使用Apps Script借助Google Maps查找最长路线的问题

问题原因与解决方案

默认情况下,Google Apps Script的Maps.newDirectionFinder()只返回最优路线(通常是最短或最快的),不会返回备选路线,这就是你脚本里routes数组长度为1的原因。网页端显示多条路线是因为自动开启了备选路线选项,但脚本需要手动开启。

修复后的脚本

function googlemaps (start_address, end_address) {
  start_address = "Starbucks, 799 A St, Hayward, CA 94541";
  end_address = "Hayward BART Station, 699 B St, Hayward, CA 94541";

  var mapObj = Maps.newDirectionFinder();
  mapObj.setOrigin(start_address);
  mapObj.setDestination(end_address);
  // 开启备选路线选项,获取所有可用路线
  mapObj.setAlternatives(true);

  var directions = mapObj.getDirections();
  Logger.log(directions["routes"]);
  Logger.log(directions["routes"].length); // 现在应该返回3

  // 额外:找出最长路线
  if (directions.routes.length > 0) {
    let longestRoute = directions.routes[0];
    let maxDistance = longestRoute.legs[0].distance.value;
    
    for (let route of directions.routes) {
      const currentDistance = route.legs[0].distance.value;
      if (currentDistance > maxDistance) {
        maxDistance = currentDistance;
        longestRoute = route;
      }
    }
    
    Logger.log("最长路线距离:" + longestRoute.legs[0].distance.text);
    Logger.log("最长路线详情:" + JSON.stringify(longestRoute, null, 2));
  }
};

关键说明

  • setAlternatives(true):这个方法会告诉Maps服务返回所有可行的备选路线,而不仅仅是最优的那一条。
  • 计算最长路线:遍历所有路线,通过legs[0].distance.value(米为单位)比较距离,找出最大值对应的路线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:40:30