如何从距离矩阵API获取duration_in_traffic

问题描述 投票:0回答:1

我想从距离矩阵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,只有从服务器发出请求时才返回。

第二是,此响应仅发送到具有高级计划的帐户。我试图查看高级计划的注册程序,但不清楚。该网站here说:“注册或新客户不再可以使用Google Maps Platform Premium计划。”那是什么意思。我目前正在使用Google Cloud Platform免费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库的文档,但找不到它。

我对这三种方法都没问题,即使有其他方法也没关系。请您帮我弄清楚我要去哪里错了。

google-maps google-maps-api-3 cors google-distancematrix-api
1个回答
0
投票
也就是说,documentation说:

[duration_in_traffic只返回给有流量数据,mode设置为driving,并且departureTime作为请求中distanceMatrixOptions字段的一部分的Google Maps Platform Premium计划客户。] >

因此,您应该使用web service来表示以下所有内容都必须为真才能获得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中的错误。
  • © www.soinside.com 2019 - 2024. All rights reserved.