使用 Google Maps API 估算流量

der*_*can 1 google-maps google-apps-script

我正在尝试调用 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);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,无论我何时运行代码,我总是得到 的结果3 hours 43 mins(尽管我已经定义了departure_timetraffic_model。有什么建议吗?

(顺便说一句,文档说我需要传入 API 密钥作为必需参数。显然 - 根据我上面的代码 - 我还没有这样做。但这并没有阻止我获得响应。这会阻止我使用这些traffic_model参数吗?)

xom*_*ena 5

您看到什么字段:持续时间或duration_in_traffic?

\n

根据文档

\n
\n

uration_in_traffic表示该路段的总持续时间。该值是根据当前和历史交通状况对交通时间的估计。请参阅 Traffic_model 请求参数,了解可用于请求返回值是乐观、悲观或最佳猜测值的选项。仅当满足以下所有条件时,才会返回流量持续时间:

\n
    \n
  • 该请求包含有效的 API 密钥或有效的 Google Maps API 高级计划客户端 ID 和签名。

    \n
  • \n
  • 该请求不包括中途停留航点。如果请求包含航点,则必须以 via: 为前缀,以避免中途停留。

    \n
  • \n
  • 该请求专门用于驾驶方向\xe2\x80\x94,模式参数设置为驾驶。

    \n
  • \n
  • 该请求包括出发时间参数。

    \n
  • \n
  • 所请求路线的交通状况可用。

    \n
  • \n
\n
\n

https://developers.google.com/maps/documentation/directions/intro#DirectionsResponseElements

\n

据我所知,您看不到 period_in_traffic 字段,因为您没有应用 API 密钥。

\n

希望能帮助到你!

\n