google-mapsgoogle-sheetsgoogle-apps-scriptsyntax

Error on script to get time and distance between two addresses


I am trying to set up a google sheet where I can pout in two addresses and get the distance and time travelled from google maps in the excel sheet

I have the script below - but it keeps coming up with an error - error is

Exception: Invalid argument: origin
GOOGLEMAPS @GOOGLEMAPS.gs:4

My script is below

function GOOGLEMAPS(start_address,end_address,return_type) {

  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 "kilometers":
      return meters / 1000;
      break;
    default:
      return "error:wrong unit type";
  }
}

Solution

  • A few things come to mind:

    1. Are you sure the addresses you're inputting in the sheet are formatted correctly? Sometimes Google Maps can be picky about that.

    2. Have you double-checked that you've enabled the Google Maps API in your Google Cloud Console for this project? Sometimes that's the culprit.

    3. It might be worth trying to hardcode a known good address just to test if it's an issue with the input or the function itself.

    4. Also, have you considered using the newer UrlFetchApp.fetch() method instead of the Maps service? I've found it to be more reliable sometimes, though it does require a bit more setup.