2017-03-20 179 views
0

嘿,我正在開發一個跟蹤系統,我必須使用谷歌地圖的API來計算ETA(預計到達時間)。 我有駕駛距離。 但我需要到達目的地的公里以便能夠預測到達時間。JavaScript-谷歌地圖API

我該如何稱下面的行車距離值?

directionsService.route(request, 
function(response, status) { 
    if (status == google.maps.DirectionsStatus.OK) { 
      (response.routes[0].legs[0].distance.value); // the distance in metres 
       return((response.routes[0].legs[0].distance.value)/1000); //distance e kilometres 
       } 
        else { 
        // oops, there's no route between these two locations 
        // every time this happens, a kitten dies 
        // so please, ensure your address is formatted properly 
       } 
      }); 


function getArrivalTime(distance, vel) { 
     return distance/vel; 
    }; 
    console.log(getArrivalTime(distance,vel)); 

回答

0

實際上,您可以在您的函數getArrivalTime中放置您的路線請求。然後,你可以簡單地創建一個變種持有的距離,將其設置爲response.routes [0] .legs [0] .distance.value)/ 1000請參閱代碼示例在這裏:

function getArrivalTime(vel) { 
    var distance; 
    directionsService.route(request, 
    function(response, status) { 
    if (status == google.maps.DirectionsStatus.OK) { 
     (response.routes[0].legs[0].distance.value); // the distance in metres 
      distance = ((response.routes[0].legs[0].distance.value)/1000); //distance e kilometres 
      } 
       else { 
       // oops, there's no route between these two locations 
       // every time this happens, a kitten dies 
       // so please, ensure your address is formatted properly 
      } 
     }); 
    return distance/vel; 
}; 
console.log(getArrivalTime(distance,vel)); 

您可能需要在return(distance,vel)周圍放置超時以確保在返回數據之前API調用已經有時間響應請求。另一個選擇是創建一個全局變量來保持距離,以便您可以在任何函數中訪問它。雖然通常最好避免全局變量,所以我會推薦我提到的第一種方法。

我希望這有助於!