简体   繁体   English

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

[英]How to fetch duration_in_traffic from distance matrix API

I want to fetch duration_in_traffic from distance matrix API.我想从距离矩阵 API 中获取 duration_in_traffic。

It works fine when I access the API Directly through URL当我通过 URL 直接访问 API 时它工作正常

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

But It does not work from code.但它不适用于代码。 here are the things that I tried.这是我尝试过的事情。

1) Tried to call the API through AJAX from client side JS. 1) 尝试从客户端 JS 通过 AJAX 调用 API。 getting CORS issue in response收到 CORS 问题作为回应

2) Tried to use JS client library 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);
            }
        }

It does not return duration_in_traffic.它不返回duration_in_traffic。 I searched about it and found two different reasons, I donno which one is correct.我搜索了一下,发现了两个不同的原因,我不知道哪个是正确的。

First is that duration_in_traffic is not supported by javascript client library, it is only returned if the request is made from server.首先是javascript客户端库不支持duration_in_traffic,只有当请求是从服务器发出时才返回。

Second is that this response is only sent to accounts with premium plan only.其次,此响应仅发送到仅具有高级计划的帐户。 I tried to see the procedure to enrolling for premium plan but its not clear.我试图查看注册高级计划的程序,但不清楚。 this site here says "The Google Maps Platform Premium Plan is no longer available for sign up or new customers.".这个网站在这里说“Google Maps Platform Premium Plan 不再可供注册或新客户使用。”。 what is that supposed to mean.那是什么意思。 I am currently using google cloud platform free 1 year and 300 dollars trial version.我目前正在使用谷歌云平台免费 1 年和 300 美元试用版。

3) I tried using nodeJS library 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);
  });

and got this response.并得到了这个回应。

    { 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' } }

I tried looking for the documentation for this nod library but could not find it.我试图寻找这个 nod 库的文档,但找不到它。

I am okay with all 3 methods or even if there is any other.我对所有 3 种方法都满意,即使还有其他方法。 would you please help me figure out where am I going wrong.你能帮我弄清楚我哪里出错了。

If you want to query the Distance Matrix client side, you should use the Distance Matrix Service which is part of the Javascript API.如果你想查询距离矩阵客户端,你应该使用距离矩阵服务,它是 Javascript API 的一部分。

That said, the documentation says:也就是说, 文档说:

The duration_in_traffic is only returned to Google Maps Platform 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. duration_in_traffic仅返回给 Google Maps Platform Premium Plan 客户,在这些情况mode ,交通数据可用, mode设置为driving ,并且departureTime时间包含在请求中的 distanceMatrixOptions 字段中。

So you should use the web service which mentions that all of the below must be true to get the duration_in_traffic :因此,您应该使用Web 服务,其中提到以下所有内容都必须为真才能获得duration_in_traffic

  • The request includes a departure_time parameter.该请求包括一个departure_time参数。
  • The request includes a valid API key, or a valid Google Maps Platform Premium Plan client ID and signature.该请求包含有效的 API 密钥或有效的 Google Maps Platform Premium Plan 客户端 ID 和签名。
  • Traffic conditions are available for the requested route.所请求路线的交通状况是可用的。
  • The mode parameter is set to driving . mode参数设置为driving

Given what you posted, it doesn't seem you have provided all of these in your requests.鉴于您发布的内容,您似乎并未在请求中提供所有这些内容。

You mentioned you tried the node JS library but what you posted is a call to the Geocoder service which is a different API and which requires to be enabled for your key, hence the error in the response This API project is not authorized to use this API .您提到您尝试过节点 JS 库,但您发布的是对 Geocoder 服务的调用,这是一个不同的 API,需要为您的密钥启用,因此响应中出现错误This API project is not authorized to use this API .

To make this work and return the duration_in_traffic , please add the drivingOptions object [1] with the fields:为了完成这项工作并返回duration_in_traffic ,请添加带有以下字段的drivingOptions 对象 [1]:

{
  departureTime: Date,
  trafficModel: TrafficModel
}

It will look similar to this example:它看起来类似于这个例子:

{
  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 [1] https://developers.google.com/maps/documentation/javascript/distancematrix#DrivingOptions

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

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