簡體   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