Home > Net >  Using Apps Script to find longest route using Google Maps
Using Apps Script to find longest route using Google Maps

Time:11-03

So I have a small script that I am using to find the distance between locations using Maps. Most people would want to use the shortest recommended route, but I am trying to find the longest. Here is the start of the current script:

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);

var directions = mapObj.getDirections();
Logger.log(directions["routes"]);
Logger.log(directions["routes"].length);

};

When I look on Google maps for the directions of the above address, I can see that there are three possible routes, but when I try to find the length of the array, it just says 1. I'm not sure what I am missing

CodePudding user response:

Modification points:

  • In your situation, you can retrieve other patterns using setAlternatives(true). Ref This has also already been mentioned in the comment.

  • In order to retrieve the longest you expect, it is required to retrieve it from the response values.

When these are reflected in your script, how about the following modification?

Modified script:

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); // Added
  var directions = mapObj.getDirections();
  var res = directions.routes.sort((a, b) => a.legs[0].distance.value > b.legs[0].distance.value ? -1 : 1)[0]; // Modified
  console.log(res.legs[0].distance.value); // Modified
  // console.log(res); // Here, you can see the object of `the longest`.
}
  • When this script is run, you can retrieve the object of the longest as res. In this modification, in order to retrieve the object of the longest, I used sort.

References:

  • Related