Google maps UrfFetchApp.fetch错误,带有路径点的google地图方向url(路径点以|分隔)
我在我的谷歌应用程序脚本(GAS)中使用谷歌地图方向。 此程序将创建一个url:Google maps UrfFetchApp.fetch错误,带有路径点的google地图方向url(路径点以|分隔),google-maps,google-maps-api-3,google-apps-script,urlfetch,Google Maps,Google Maps Api 3,Google Apps Script,Urlfetch,我在我的谷歌应用程序脚本(GAS)中使用谷歌地图方向。 此程序将创建一个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
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);
}
并在GAS中使用UrlFetchApp.fetch()获得结果
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;
}
}
}
服务URL如下所示:
“美国北卡罗来纳州罗利市德累斯顿Ln 27612&目的地=美国北卡罗来纳州罗利市首都大道5000号&航路点=7928心轴路,美国北卡罗来纳州罗利市德累斯顿Ln 27616 | 6501北卡罗来纳州罗利市德累斯顿Ln 27612&模式=驾驶和备选方案=错误和钥匙=MyKeyCodeHere”
我可以使用此serviceUrl在浏览器中获取结果手册。但是UrlFetchApp.fetch()不能
我发现如果serviceUrl没有“|”,它就可以工作。但是我需要多个航路点,并且在Url中用“|”分隔(我想使用许多航路点-接近23个航路点-所以我需要在Url中使用“|”)。请参见关于航路点:
//由|分隔的多个航路点。
函数createWayPoint(arrayWayPoint){
var航路点=”;
对于(变量i=0;i
有人帮我吗?多谢各位 使用
encodeURIComponent()
到如下示例中的位置如何
示例脚本:
如果这不起作用,我很抱歉。我认为你的问题不是很清楚。但我能想到的一个可能导致
UrlFetchApp.fetch()
无法加载页面的原因是url中存在空格。谢谢你的回答。如果没有“|”(有空格但没有“|”),此Url仍然可以工作。我尝试通过encodeURIComponent(serviceUrl)对其进行编码;但是它不能工作。你是对的。非常感谢你。
// 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;
}
function createUrl(origin, destination,wayPoint) {
var Your_API_KEY = "my code here";
var serviceUrl = "https://maps.googleapis.com/maps/api/directions/json?"
+"origin="+encodeURIComponent(origin)
+"&destination="+encodeURIComponent(destination)
+"&waypoints=" + encodeURIComponent("optimize:true|"+ wayPoint)
+"&mode="+Maps.DirectionFinder.Mode.DRIVING
+"&alternatives="+Boolean(0)
+"&key="+Your_API_KEY;
return(serviceUrl);
}