Script, Map Distance "Shortest Route"

58 views
Skip to first unread message

Will V

unread,
Sep 14, 2023, 5:06:04 AM9/14/23
to Google Apps Script Community
hi  could use some help/advice, pls.

I managed to figure how to apply the following script that basically calculates the distance between two addresses in miles. I wonder if there is anything we can add to that script to say "generate the miles for the SHORTEST route" for example, when we search any address in Maps, Google gives several routes, one is usually always less miles. maybe a script could somehow pick up the "shortest miles distance" route?


function onEdit(e) {  
  var row = e.range.getRow();
  var col = e.range.getColumn();
  var sheetName = e.source.getActiveSheet().getName();
  if((col == 3 || col == 4) && sheetName=="Tracker"){
    var add1 = e.source.getActiveSheet().getRange("C"+row);
    var add2 = e.source.getActiveSheet().getRange("D"+row);
    if(!(add1.isBlank() || add2.isBlank())) {
      e.source.getActiveSheet().getRange("E"+row).setValue(GOOGLEMAPS(add1.getValue(),add2.getValue(),"miles"));
    } else {
      e.source.getActiveSheet().getRange("E"+row).setValue("");
    }
  }
}

/**
* Get Distance between 2 different addresses.
* @param start_address Address as string Ex. "300 N LaSalles St, Chicago, IL"
* @param end_address Address as string Ex. "900 N LaSalles St, Chicago, IL"
* @param return_type Return type as string Ex. "miles" or "kilometers" or "minutes" or "hours"
* @customfunction
*/

function GOOGLEMAPS(start_address,end_address,return_type) {

  // Nov 2017
  // improvements needed
 
  var mapObj = Maps.newDirectionFinder();
  mapObj.setOrigin(start_address);
  mapObj.setDestination(end_address);
  var directions = mapObj.getDirections();
 
  var getTheLeg = directions["routes"][0]["legs"][0];
 
  var meters = getTheLeg["distance"]["value"];
 
  switch(return_type){
    case "miles":
      return meters * 0.000621371;
      break;
    case "minutes":
        // get duration in seconds
        var duration = getTheLeg["duration"]["value"];
        //convert to minutes and return
        return duration / 60;
      break;
    case "hours":
        // get duration in seconds
        var duration = getTheLeg["duration"]["value"];
        //convert to hours and return
        return duration / 60 / 60;
      break;      
    case "kilometers":
      return meters / 1000;
      break;
    default:
      return "Error: Wrong Unit Type";
   }
 
}

cwl...@gmail.com

unread,
Sep 15, 2023, 10:09:21 AM9/15/23
to Google Apps Script Community
I would look at the API documentation. But this line give a hint that there may be more than a single route returned:

var getTheLeg = directions["routes"][0]["legs"][0];     
What does it look like when you console.log(directions) ?  (or directions["routes"])  ?
Reply all
Reply to author
Forward
0 new messages