在googlesheets脚本中寻找多个点之间的距离

时间:2014-03-03 00:53:22

标签: google-apps-script google-sheets

// adapted from developers.google.com/apps-script/quickstart/macros
function drivingDistance(origin, waypoint, destination) {
    var directions = getDirections_(origin, destination);
    return directions.routes[0].legs[0].distance.value;
}

function getDirections_(origin, waypoint, destination) {
    var directionFinder = Maps.newDirectionFinder();
    directionFinder.setOrigin(origin);
    directionFinder.addWaypoint(waypoint);
    directionFinder.setDestination(destination);

    var directions = directionFinder.getDirections();
    if (directions.routes.length == 0) {
    throw 'Unable to calculate directions between these addresses.';
    }
    return directions;
}

此脚本最初检查A列的原点,然后检查B列的目的地。我试图使用addWaypoint函数添加第3个点,但一直没有成功。我阅读了API并尝试了一些不同的变体,但我担心我再次失败了。如何添加多个目的地或航点

2 个答案:

答案 0 :(得分:2)

当有多个航点时,route将由多个legs组成,每个distance都有自己的=drivingDistance(A2:D2) 。因此,一旦你计算了路线,你仍然需要经过每条腿并总结各个距离以得到最终值。

一旦我们确定了一个中点,我们肯定会想要两个。一旦我们有两个,为什么不三个?最后,为什么不是任意数量的航路点?

有关具有任意参数的自定义函数如何在电子表格中运行的示例,请参阅Accept Arbitrary Number of Arguments in Google Scripts Custom Function?

此修改后的脚本处理包含任意数量点的路径。表格中的自动完成功能完全支持它。它可以处理航点列表或一系列单元格。它也有很多评论来解释每一步。

基本用途:

=TEXT(drivingDistance(A2:D2)/1000,"#,### k\m")

更高级的使用,输出更容易理解:

/**
 * Calculate the driving distance (in meters) along a route.
 *
 * @param {"london","manchester","liverpool"} route
 *        Comma separated ordered list of two or more map
 *        waypoints to include in route. First point
 *        is 'origin', last is 'destination'.
 *
 * @customfunction
 */
function drivingDistance(route) {
  // From gist.github.com/mogsdad/e07d537ff06f444866c5
  // Adapted from developers.google.com/apps-script/quickstart/macros
  // If a range of cells is passed in, 'route' will be a two-dimensional array.
  // Test for an array, and if we have one, collapse it to a single array.
  if (route.constructor === Array) {
    var args = route.join(',').split(',');
  }
  else {
    // No array? Grab the arbitrary arguments passed to the function.
    args = arguments;
  }

  // Just one rule to a route - we need a beginning and an end
  if (args.length < 2) throw new Error( "Must have at least 2 waypoints." )

  // Pass our waypoints to getDirections_(). Tricky bit, this.
  var directions = getDirections_.apply(this, args);

  // We have our directions, grab the first route's legs
  var legs = directions.routes[0].legs;

  // Loop through all legs, and sum up distances
  var dist = 0;
  for (var i=0; i<legs.length; i++) {
    dist += legs[i].distance.value;
  }

  // Done - return the value in meters
  return dist;
}

/**
 * Use Maps service to get directions for a route consisting of an arbitrary
 * set of waypoints.
 */
function getDirections_(route) {
  // Just one rule to a route - we need a beginning and an end
  if (arguments.length < 2) throw new Error( "Must have at least 2 waypoints." )

  // Assume first point is origin, last is destination.
  var origin = arguments[0];
  var destination = arguments[arguments.length-1];

  // Build our route; origin + all midpoints + destination
  var directionFinder = Maps.newDirectionFinder();
  directionFinder.setOrigin(origin);
  for ( var i=1; i<arguments.length-1; i++ ) {
    directionFinder.addWaypoint(arguments[i]);
  }
  directionFinder.setDestination(destination);

  // Get our directions from Map service;
  // throw an error if no route can be calculated.
  var directions = directionFinder.getDirections();
  if (directions.routes.length == 0) {
    throw 'Unable to calculate directions between these addresses.';
  }
  return directions;
}

screenshot

代码

足够的叽叽喳喳,只要给我代码! (gist.github.com上提供了更新的代码。)

{{1}}

答案 1 :(得分:1)

function drivingDistance()中缺少参数。我改变了

var directions = getDirections_(origin, destination);

var directions = getDirections_(origin, waypoint, destination);
                                        ^^^^^^^^

这是更新的代码,带有测试功能

function testDistance() {
 var dist = drivingDistance("london","manchester","liverpool");
 Logger.log( dist );   // 321563 (meters)
}

function drivingDistance(origin, waypoint, destination) {
    var directions = getDirections_(origin, waypoint, destination);
    return directions.routes[0].legs[0].distance.value;
}

function getDirections_(origin, waypoint, destination) {
    var directionFinder = Maps.newDirectionFinder();
    directionFinder.setOrigin(origin);
    directionFinder.addWaypoint(waypoint);
    directionFinder.setDestination(destination);

    var directions = directionFinder.getDirections();
    if (directions.routes.length == 0) {
      throw 'Unable to calculate directions between these addresses.';
    }
    return directions;
}

祝你好运。学习如何编程需要时间。我建议你找一个教Java Script的网站。希望你能使用电子表格。

PS:如果您想要更具可读性的结果,可以更改drivingDistance()的最后一行,以提供distance.text而不是distance.value。在伦敦 - 曼彻斯特 - 利物浦的例子中,结果将是"322 km"