繁体   English   中英

如何从距离矩阵 API 中获取 duration_in_traffic

[英]How to fetch duration_in_traffic from distance matrix API

我想从距离矩阵 API 中获取 duration_in_traffic。

当我通过 URL 直接访问 API 时它工作正常

https://maps.googleapis.com/maps/api/distancematrix/json?origins=Boston,MA&destinations=Lexington,MA&departure_time=now&key=MY_KEY

但它不适用于代码。 这是我尝试过的事情。

1) 尝试从客户端 JS 通过 AJAX 调用 API。 收到 CORS 问题作为回应

2)尝试使用JS客户端库

        var base = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric";
        var source = "&origins=" + element["Origin Name"] + " , " + element["Origin Street"] + " , " + element["Origin City"] + " , " + element["Origin State"] + " , " + element["Origin County"] + " , " + element["Origin Postal"];
        var destination = "&destinations=" + element["Destination Name"] + " , " + element["Destination Street"] + " , " + element["Destination City"] + " , " + element["Destination State"] + " , " + element["Destination County"] + " , " + element["Destination Postal"];
        var key = "&key=MY_KEY";
        var time = "&departure_time=";
        try {
            time += new Date().setHours(24 + parseInt(element["Pickup Time"].split(":")[0]), parseInt(element["Pickup Time"].split(":")[1]), 0, 0);
        }
        catch{
            time += new Date().setHours(0, 0, 0, 0);
        }
        console.log(time);
        var url = base + time + source + destination + key + "&transit_mode=driving";

        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
            {
                origins: [source],
                destinations: [destination],
                travelMode: 'DRIVING',
            }, callback);

        if (lastSource != "empty") {
            service.getDistanceMatrix(
                {
                    origins: [lastSource],
                    destinations: [source],
                    travelMode: 'DRIVING',
                }, callback2);
        }

        lastSource = source;

        function callback(response, status) {
            try {
                element["TRIP DISTANCE"] = (parseFloat(response.rows["0"].elements["0"].distance.text.replace(/ km/g, '')) / 1.609).toFixed(2) + " Miles";
                console.log(response.rows["0"].elements["0"].distance.text);
                console.log(element["TRIP DISTANCE"]);
                element["TRIP TRAVEL TIME "] = response.rows["0"].elements["0"].duration.text;
            }
            catch (e) {
                console.log(e);
            }
        }
        function callback2(response, status) {
            try {
                element["ROUTE DISTANCE"] = (parseFloat(response.rows["0"].elements["0"].distance.text.replace(/ km/g, '')) / 1.609).toFixed(2) + " Miles";
                console.log(response.rows["0"].elements["0"].distance.text);
                console.log(element["TRIP DISTANCE"]);
                element["ROUTE TRAVEL TIME"] = response.rows["0"].elements["0"].duration.text;
            }
            catch (e) {
                console.log(e);
            }
        }

它不返回duration_in_traffic。 我搜索了一下,发现了两个不同的原因,我不知道哪个是正确的。

首先是javascript客户端库不支持duration_in_traffic,只有当请求是从服务器发出时才返回。

其次,此响应仅发送到仅具有高级计划的帐户。 我试图查看注册高级计划的程序,但不清楚。 这个网站在这里说“Google Maps Platform Premium Plan 不再可供注册或新客户使用。”。 那是什么意思。 我目前正在使用谷歌云平台免费 1 年和 300 美元试用版。

3)我尝试使用nodeJS

 const googleMapsClient = require('@google/maps').createClient({
  key: 'MY_KEY',
  Promise: Promise
});

googleMapsClient.geocode({address: '1600 Amphitheatre Parkway, Mountain View, CA'})
  .asPromise()
  .then((response) => {
    console.log(response.json.results);
  })
  .catch((err) => {
    console.log(err);
  });

并得到了这个回应。

    { status: 200,
  headers:
   { 'content-type': 'application/json; charset=UTF-8',
     date: 'Sat, 07 Dec 2019 11:03:05 GMT',
     pragma: 'no-cache',
     expires: 'Fri, 01 Jan 1990 00:00:00 GMT',
     'cache-control': 'no-cache, must-revalidate',
     'access-control-allow-origin': '*',
     server: 'mafe',
     'x-xss-protection': '0',
     'x-frame-options': 'SAMEORIGIN',
     'server-timing': 'gfet4t7; dur=19',
     'alt-svc':
      'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000',
     'accept-ranges': 'none',
     vary: 'Accept-Language,Accept-Encoding',
     connection: 'close' },
  json:
   { error_message: 'This API project is not authorized to use this API.',
     results: [],
     status: 'REQUEST_DENIED' },
  requestUrl:
   'https://maps.googleapis.com/maps/api/geocode/json?address=1600%20Amphitheatre%20Parkway%2C%20Mountain%20View%2C%20CA&key=MY_KEY',
  query:
   { address: '1600 Amphitheatre Parkway, Mountain View, CA',
     key: 'MY_KEY' } }

我试图寻找这个 nod 库的文档,但找不到它。

我对所有 3 种方法都满意,即使还有其他方法。 你能帮我弄清楚我哪里出错了。

如果你想查询距离矩阵客户端,你应该使用距离矩阵服务,它是 Javascript API 的一部分。

也就是说, 文档说:

duration_in_traffic仅返回给 Google Maps Platform Premium Plan 客户,在这些情况mode ,交通数据可用, mode设置为driving ,并且departureTime时间包含在请求中的 distanceMatrixOptions 字段中。

因此,您应该使用Web 服务,其中提到以下所有内容都必须为真才能获得duration_in_traffic

  • 该请求包括一个departure_time参数。
  • 该请求包含有效的 API 密钥或有效的 Google Maps Platform Premium Plan 客户端 ID 和签名。
  • 所请求路线的交通状况是可用的。
  • mode参数设置为driving

鉴于您发布的内容,您似乎并未在请求中提供所有这些内容。

您提到您尝试过节点 JS 库,但您发布的是对 Geocoder 服务的调用,这是一个不同的 API,需要为您的密钥启用,因此响应中出现错误This API project is not authorized to use this API .

为了完成这项工作并返回duration_in_traffic ,请添加带有以下字段的drivingOptions 对象 [1]:

{
  departureTime: Date,
  trafficModel: TrafficModel
}

它看起来类似于这个例子:

{
  origins: [{lat: 55.93, lng: -3.118}, 'Greenwich, England'],
  destinations: ['Stockholm, Sweden', {lat: 50.087, lng: 14.421}],
  travelMode: 'DRIVING',
  drivingOptions: {
    departureTime: new Date(),
    trafficModel: 'optimistic'
  }
}

[1] https://developers.google.com/maps/documentation/javascript/distancematrix#DrivingOptions

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM