首页 > 解决方案 > 如何从距离矩阵 API 中获取 duration_in_traffic

问题描述

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

其次,此响应仅发送到仅具有高级计划的帐户。我试图查看注册高级计划的程序,但不清楚。这个网站在这里 说“谷歌地图平台高级计划不再适用于注册或新客户。”。那应该是什么意思。我目前正在使用谷歌云平台免费 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 种方法都很好,即使还有其他方法。请你帮我弄清楚我哪里出错了。

标签: google-mapsgoogle-maps-api-3google-distancematrix-api

解决方案


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

也就是说,文档说:

duration_in_traffic仅在交通数据可用的情况下返回给 Google Maps Platform Premium Plan 客户,mode设置为driving,并departureTime作为请求中 distanceMatrixOptions 字段的一部分包含在内。

因此,您应该使用提到以下所有内容都必须为真才能获得的网络服务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


推荐阅读