我正在尝试调用Google Maps API来获取两点之间的旅行时间( 包括 流量)。这是我到目前为止所得到的:
function test(){
//Info: https://developers.google.com/maps/documentation/directions/intro
var baseUrl = "https://maps.googleapis.com/maps/api/directions/json?";
var origin = "Redmond+WA";
var destination = "Salem+OR";
var departureTime = "now";
var trafficModel = "pessimistic";
var url = baseUrl + "origin=" + origin + "&destination=" + destination + "&departure_time=" + departureTime + "&traffic_model=" + trafficModel;
var response = UrlFetchApp.fetch(url);
Logger.log("Google Maps API: " + JSON.parse(response).routes[0].legs[0].duration.text);
Logger.log("Full response from API: \n" + response);
}
不幸的是,无论何时运行代码,我都会得到3 hours 43 mins
的结果(尽管事实上我已经定义了departure_time
和traffic_model
。有什么建议吗?
(旁注,documentation表示我需要传递API密钥作为必需参数。显然 - 根据我上面的代码 - 我还没有这样做。但它没有阻止我收到回复。这是否会妨碍我使用traffic_model
参数?)
答案 0 :(得分:3)
您看到哪个字段:duration或duration_in_traffic?
根据文件
duration_in_traffic 表示此段的总持续时间。该值是基于当前和历史交通状况的交通时间的估计。请参阅traffic_model请求参数,以获取可用于请求返回值是乐观,悲观或最佳猜测估计的选项。仅当满足以下所有条件时,才会返回流量持续时间:
该请求包含有效的API密钥或有效的Google Maps API Premium Plan客户ID和签名。
请求不包括中途停留点。如果请求包含航点,则必须以via为前缀:以避免中途停留。
该请求专门针对行车路线 - 模式参数设置为行驶。
请求包含departure_time参数。
所需路线的交通状况可用。
https://developers.google.com/maps/documentation/directions/intro#DirectionsResponseElements
我知道您无法查看duration_in_traffic字段,因为您没有应用API密钥。
希望它有所帮助!