大家好,今天本人给大家带来文章《Google 地图 api 和 period_in_traffic》,文中内容主要涉及到,如果你对golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
问题内容
我正在尝试了解 distancematrix api。当我在浏览器上执行此操作时:
https://maps.googleapis.com/maps/api/distancematrix/JSON?origins=14.614786,121.046587&destinations=14.610301,121.080233&mode=driven&language=en&departure_time=now&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"
}
但是当我使用地图 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())
}
今天关于《Google 地图 API 和 period_in_traffic》的内容介绍就到此结束.