我正在努力理解DistanceMatrix API。当我在浏览器上这样做时:
https://maps.googleapis.com/maps/api/distancematrix/json?origins=14.614786,121.046587&目的地=14.6103301121.080233&mode=驾驶&language=en&departure_time=现在&key=MY_key
我得到了duration_in_traffic。
{
"destination_addresses" : [
"17 Orchard Rd, Bagumbayan, Quezon City, 1109 Metro Manila, Philippines"
],
"origin_addresses" : [ "74 C. Benitez St, Quezon City, Metro Manila, Philippines" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "8.5 km",
"value" : 8470
},
"duration" : {
"text" : "23 mins",
"value" : 1406
},
"duration_in_traffic" : {
"text" : "35 mins",
"value" : 2112
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
但是当我有它在golang使用地图API
我没有得到duration_in_traffic,只返回空
r := &maps.DistanceMatrixRequest{
Language: *language,
DepartureTime: "now",
ArrivalTime: *arrivalTime,
}
以下是结果
{
"origin_addresses": [
"74 C. Benitez St, Quezon City, Metro Manila, Philippines"
],
"destination_addresses": [
"17 Orchard Rd, Bagumbayan, Quezon City, 1109 Metro Manila, Philippines"
],
"rows": [
{
"elements": [
{
"status": "OK",
"distance": {
"text": "8.5 km",
"value": 8470
},
"duration": {
"value": 1406,
"text": "23m26s"
},
"duration_in_traffic": null
}
]
}
]
}
我做错了什么?
编辑:
r := &maps.DistanceMatrixRequest{
Origins: strings.Split(origins, "|"),
Destinations: strings.Split(destinations, "|"),
Language: "en",
DepartureTime: "now",
Mode: maps.TravelModeDriving,
Units: maps.UnitsMetric,
}
resp, err := client.DistanceMatrix(context.Background(), r)
if err != nil {
return c.JSON(http.StatusBadRequest, err)
}
return c.JSON(http.StatusOK, resp)
遇到了和你相同的问题,对你帖子的编辑解决了我的问题。
为了向稍后可能出现的任何人澄清解决方案,问题是我没有在请求中指定DepartureTime
。
如果在DepartureTime
被注释掉的情况下运行以下代码,它将打印:
go run traffic.go
Duration in minutes: 0.000000
但在请求中指定了DepartureTime: "now"
后,它会给出:
go run traffic.go
Duration in minutes: 135.966667
以下是完整的工作示例。
package main
import (
"fmt"
"log"
"golang.org/x/net/context"
"googlemaps.github.io/maps"
)
func main() {
c, err := maps.NewClient(maps.WithAPIKey("my-api-key-here"))
if err != nil {
log.Fatalf("fatal error: %s", err)
}
r := &maps.DistanceMatrixRequest{
Origins: []string{"Newark, DE"},
Destinations: []string{"Charles Town, WV"},
Units: maps.UnitsImperial,
Language: "en",
// Must specify DepartureTime in order to get DurationInTraffic in response
DepartureTime: "now",
}
route, err := c.DistanceMatrix(context.Background(), r)
if err != nil {
log.Fatalf("fatal error: %s", err)
}
fmt.Printf("Duration in minutes: %fn", route.Rows[0].Elements[0].DurationInTraffic.Minutes())
}
另一个潜在的问题是,如果谷歌没有流量数据,它不会返回duration_in_traffic。
文件状态:
只有在以下所有情况下,才会返回流量中的持续时间true:
The request includes a departure_time parameter. The request includes a valid API key, or a valid Google Maps Platform Premium Plan client ID and signature. Traffic conditions are available for the requested route. The mode parameter is set to driving.