我正在尝试了解DistanceMatrix API。当我在浏览器上执行此操作时:
我得到了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"
}
但是当我使用 map API将其放在golang中时
我没有得到duration_in_traffic并且仅返回null
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: %f\n", route.Rows[0].Elements[0].DurationInTraffic.Minutes())
}