2017-04-21 168 views
0

我在地圖上有一個起點座標。我有多個(100)端點來計算從起點到終點的總距離。 起點是我的辦公室,終點是我客戶的位置。我想計算總距離。谷歌地圖從一個起點到多個終點的方向

我用循環於JavaScript

for (var i = 0; i < destinations.length; i++) { 

    var request = { 
     origin: "60.758447, 69.385923", 
     destination: destinations[i], 
     travelMode: google.maps.DirectionsTravelMode.DRIVING 
    }; 

    directionsService.route(request, function (response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
      var directionsDisplay = new google.maps.DirectionsRenderer(); 
      directionsDisplay.setMap(map); 
      directionsDisplay.setDirections(response); 
      totalKM = totalKM + (response.routes[0].legs[0].distance.value/1000); 
      distanceInput.value = totalKM; 
      console.log(totalKM) 
     } 
    }); 

}; 

但這個循環只適用10個目的地。我可以在控制檯日誌中看到這一點。谷歌是否限制查詢限制?

+2

你是對的,Google確實限制了您可以快速連續進行的'directionService'調用的數量。 [請點擊此處](https://developers.google.com/maps/documentation/javascript/directions#usageLimits)瞭解您可以執行多少操作。如果你在if(status == google.maps.DirectionsStatus.OK)之外檢查,我確定這個狀態是'OVER_QUERY_LIMIT'或類似的東西。 – George

+1

如果您只需要駕駛距離,請嘗試距離矩陣。 – geocodezip

+0

是的,我只需要距離總和。 – barteloma

回答

0

在發佈的其中一條評論中,提到了距離矩陣API。我會推薦這個,因爲你只有一個出發地和多個目的地。使用路線API,您只能擁有一個起點和終點對,但通過距離矩陣API,您可以擁有多個終點和起點。距離矩陣API還允許每個請求100個元素(number_of_elements = number_of_origins * number_of_destinations)。這將允許您在一個請求中擁有一個來源和100個目的地。請在這裏看到使用限制:

https://developers.google.com/maps/documentation/distance-matrix/usage-limits

當你從API的響應,就可以得到每個元素的距離,:

for(i = 0; i < response.rows[0].elements.length; i++){ 
    totalDistance += response.rows[0].elements[i].distance.value; 
} 

它的元素0的行數組中,因爲你只有一個來源,如果您有多個來源,則需要循環多行。

我還修改了文檔中的一個Google Distance Matrix API示例,以總結3個目標從一個來源到這個目標的距離。唯一的區別是在你的應用程序中你會有更多的目的地,但邏輯應該是一樣的。請注意,我把我的API密鑰出這個小提琴的安全,請輸入您自己的樣品工作:

https://jsfiddle.net/o0wyq4bo/1/

我希望這有助於!