I use Google map direction on my Google Apps Script (GAS). This program create a url:
function createUrl(origin, destination,wayPoint) {
var Your_API_KEY = "my code here";
var serviceUrl = "https://maps.googleapis.com/maps/api/directions/json?"
+"origin="+origin
+"&destination="+destination
+"&waypoints=optimize:true|"+ wayPoint
+"&mode="+Maps.DirectionFinder.Mode.DRIVING
+"&alternatives="+Boolean(0)
+"&key="+Your_API_KEY;
return(serviceUrl);
}
and use UrlFetchApp.fetch() in GAS to get result.
function test () {
var origin = "6501 Dresden Ln, Raleigh, NC 27612, USA";
var destination = "5000 Capital Blvd, Raleigh, NC 27616, USA ";
var items = ["7928 Mandrel Way, Raleigh, NC 27616, USA"];
var waypoints = createWayPoint(items);
var serviceUrl = createUrl(origin,destination,waypoints);
Logger.log (serviceUrl);
var options= {
muteHttpExceptions:true,
contentType: "application/json",
};
var response = UrlFetchApp.fetch(serviceUrl,options); //ERROR HERE
if(response.getResponseCode() == 200) {
var directions = JSON.parse(response.getContentText());
if (directions !== null){
// do something;
}
}
}
The serviceUrl like that:
"https://maps.googleapis.com/maps/api/directions/json?origin=6501 Dresden Ln, Raleigh, NC 27612, USA&destination=5000 Capital Blvd, Raleigh, NC 27616, USA &waypoints=7928 Mandrel Way, Raleigh, NC 27616, USA | 6501 Dresden Ln, Raleigh, NC 27612&mode=driving&alternatives=false&key= MyKeyCodeHere"
I can use this serviceUrl to get result manual in the browser. But UrlFetchApp.fetch() can not.
I found that if serviceUrl has not "|", it can work. But I need multi waypoints and it separated by "|" in Url (I want to use many waypoints - near 23 waypoints - so I need | in the Url). See about waypoints: https://developers.google.com/maps/documentation/directions/intro#Waypoints
// multi waypoints separated by |.
function createWayPoint (arrayWayPoint){
var waypoints = "";
for (var i = 0; i < arrayWayPoint.length; i++) {
var address = arrayWayPoint[i];
if (address !== "") {
if (i==0){
waypoints = arrayWayPoint[0];
}
else {
waypoints = waypoints + " | " + arrayWayPoint[i];
}
}
}
return waypoints;
}
Anyone help me? Thank you very much.