I'm trying to make a script which works out the fastest route to pass multiple locations, with the help of the routexl API. However, everything I try seems to come up with an error 409 Truncated server response. My code is as follows.
function myFunctionpost() {
var url = "https://api.routexl.nl/distances";
var places = [{"address":"1","lat":"52.05429","lng":"4.248618"},{"address":"2","lat":"52.076892","lng":"4.26975"},{"address":"3","lat":"51.669946","lng":"5.61852"}];
var locations = JSON.stringify(places);
var headers = {
"Authorization":"Basic " + Utilities.base64Encode("Username:password"),
"Content-Type":"application/json"
};
var options = {
'method' : 'post',
'headers' : headers,
'contentType': 'application/json',
'payload' : locations,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, options);
//var json = response.getContentText();
//var data = JSON.parse(json);
Logger.log(response);
}
The 409 error indicates there is no input found. I am no Google Apps expert, but the RouteXL API expects "locations" as input parameter. In your example the locations JSON is posted without the locations key.
Update: after some testing on Google Apps Script, I also found the ContentType needs to be adjusted.
Here is an example that worked for me:
function myFunctionpost() {
var url = "https://api.routexl.nl/distances";
var places = [{"address":"1","lat":"52.05429","lng":"4.248618"},{"address":"2","lat":"52.076892","lng":"4.26975"},{"address":"3","lat":"51.669946","lng":"5.61852"}];
var locations = JSON.stringify(places);
var headers = {
"Authorization":"Basic " + Utilities.base64Encode("username:password")
};
var options = {
'method' : 'post',
'headers' : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : {'locations': locations},
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, options);
//var json = response.getContentText();
//var data = JSON.parse(json);
Logger.log(response);
}