2016-09-29 53 views
-1

我在應用程序中集成了Google Maps JavaScript API。我需要通過給定的路徑來計算行駛距離。如何從Google Maps JavaScript API中的給定路徑值獲取距離?

路徑是等,

var path = [ 
      {lat: 36.579, lng: -118.292}, 
      {lat: 36.606, lng: -118.0638}, 
      {lat: 36.433, lng: -117.951}, 
      {lat: 36.588, lng: -116.943}, 
      {lat: 36.34, lng: -117.468}, 
      {lat: 36.24, lng: -116.832}]; 

使用上述值需要計算距離。給我你的寶貴意見。

+0

離哪裏到哪裏的陣列的版本? – jeerbl

回答

1

要使用Google Maps Javascript API v3 spherical geometry distance methods,「點」需要爲google.maps.LatLng對象,而不是google.maps.LatLngLiteral對象。

至少有四個選項:

  1. 您google.maps.LatLngLiterals的數組轉換爲google.maps.LatLng物件。
var path = [ 
     new google.maps.LatLng(36.579, -118.292), 
     new google.maps.LatLng(36.606, -118.0638), 
     new google.maps.LatLng(36.433, -117.951), 
     new google.maps.LatLng(36.588, -116.943), 
     new google.maps.LatLng(36.34, -117.468), 
     new google.maps.LatLng(36.24, -116.832)]; 
var distanceInMeters = google.maps.geometry.spherical.computeLength(path); 
  • 創建與google.maps.LatLngLiterals的陣列的google.maps.Polyline,然後調用.getPath在該折線。
  • var polyline = new google.maps.Polyline({ 
         map: map, 
         path: path 
    }); 
    var distanceInMeters = google.maps.geometry.spherical.computeLength(polyline.getPath()); 
    
  • 轉換您座標google.maps.LatLng並調用計算距離上每對,積累的距離。
  • var distanceInMeters = 0; 
    for (var i=0; i<path.length-1; i++) { 
        distanceInMeters += google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(path[i].lat, path[i].lng),new google.maps.LatLng(path[i+1].lat, path[i+1].lng)); 
    } 
    
  • 寫自己haversine公式即需要LatLngLiterals
  • 相關問題