Google 地图 javascript 库是否支持交通信息?

Does the Google Maps javascript library support traffic information?

我想在我的网络应用程序的前端获取交通信息。在后端,这可以使用以下 GET 请求轻松实现: https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=...&destinations=...&key=...&travelMode=DRIVING&departure_time=1542600800

然而,当使用 Google 地图的客户端 javascript 库并发出如下请求时:

service.getDistanceMatrix({
  origins: '...',
  destinations: '...',
  mode: 'driving',
  unitSystem: window.google.maps.UnitSystem.METRIC,
  avoidHighways: false,
  avoidTolls: false,
  transitOptions: {
    departureTime: new Date('2018-11-18T06:20:00.000'),
  },
}

我收到以下响应,其中持续时间信息不会改变,无论我使用什么出发时间。

destinationAddresses: ["..."]
originAddresses: ["..."]
    distance: {text: "27.3 km", value: 27256}
    duration: {text: "1 hour 1 min", value: 3689}

所以我的问题是:我是做错了什么还是请求的驾驶交通信息不适用于 JS Google 地图库

是的,您应该能够获得客户端库的流量持续时间。我的猜测是您将 departure_time 嵌套到 transitOptions so it will be ignored when using travelMode: driving. From the Documentation:

transitOptions (optional) — Options that apply only to requests where travelMode is TRANSIT.

由于您正在尝试获取驾驶响应,请尝试使用 drivingOptions 选项:

service.getDistanceMatrix({
    origins: '...',
    destinations: '...',
    travelMode: 'DRIVING',
    unitSystem: window.google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false,
    drivingOptions: {
        departureTime: new Date()
    }
}

duration 字段显然不包含交通信息,duration_in_traffic 对象包含,它有以下要求。来自 Google DistanceMatrix Documentation:

duration_in_traffic: The length of time it takes to travel this route taking into account current traffic conditions, expressed in seconds (the value field) and as text. The textual value is formatted according to the unitSystem specified in the request (or in metric, if no preference was supplied). The duration_in_traffic is only returned to Google Maps APIs Premium Plan customers where traffic data is available, the mode is set to driving, and departureTime is included as part of the distanceMatrixOptions field in the request.