2014-10-11 70 views
0

我無法爲我的谷歌地圖路線添加中途停留點。這是我下面的calcRoute函數。基本上我有一個稱爲waypts的latlng對象數組,waypts [0]和waypts [waypts.length-1]之間的所有點應該是中途停留點。我知道,我只是需要遍歷這些點和中途停留的東西是這樣的:添加中途停留點到航點

<script type="text/javascript"> 
     var directionsDisplay; 
     var directionsService = new google.maps.DirectionsService(); 
     var map; 
     var phpway = <?php echo json_encode($phpway); ?>; 
     var waypts = []; 

     for(var i = 0; i < phpway.length; i+=2){ 
     waypts.push(new google.maps.LatLng(phpway[i], phpway[i+1])); 
     } 

     function initialize() { 
     directionsDisplay = new google.maps.DirectionsRenderer(); 
     var chicago = new google.maps.LatLng(41.850033, -87.6500523); 
     var mapOptions = { 
      zoom: 6, 
      center: chicago 
     } 
     map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); 
     directionsDisplay.setMap(map); 
     } 

     function calcRoute() { 
     var start = waypts[0]; 
     var end = waypts[waypts.length-1]; 
     var mywaypts = []; 
     for (var i = 1; i < waypts.length-1; i++) { 

      mywaypts.push({ 
       location:waypts[i], 
       stopover:true}); 

     } 

     var request = { 
      origin: start, 
      destination: end, 
      waypoints: mywaypts, 
      optimizeWaypoints: true, 
      travelMode: google.maps.TravelMode.DRIVING 
     }; 
     directionsService.route(request, function(response, status) { 
      if (status == google.maps.DirectionsStatus.OK) { 
      directionsDisplay.setDirections(response); 
      var route = response.routes[0]; 

      } 
     }); 
     } 

     google.maps.event.addDomListener(window, 'load', initialize); 
     </script> 

回答

0

你不應該包括你的開始/結束點,在您的航點陣列,只是通過你的waypts陣列在你的要求這方法:

var request = { 
    origin : start, 
    destination : end, 
    waypoints: waypts, 
    travelMode : google.maps.TravelMode.DRIVING 
}; 

見文件:https://developers.google.com/maps/documentation/javascript/directions?hl=FR#Waypoints

+0

你可以看看爲什麼它現在無法正常工作。我已經使用你的谷歌地圖的例子,並創建一個新的數組,包含所有的中點。我上面編輯了我的問題,現在看起來如此。 – Deveram 2014-10-11 13:38:14

+0

你可以添加一個你的phpway值的樣本嗎? – 2014-10-11 14:06:38

+0

[「37.78772866390086」,「-122.468891143798」,「37.78474404781106」,「-122.397308349609」,「37.76886929179321」,「-122.451210021972」]是使用console.log(phpway)輸出的內容 – Deveram 2014-10-11 14:10:05