2017-03-04 86 views
1

這是我的代碼,我試圖讓地圖會顯示多條路線。我聽說我需要多個對象,但實際上我不知道該怎麼做。有人能幫我嗎?谷歌地圖Api V3多個路線代碼不起作用

<script> 

    var mybr = document.createElement('br'); 

     function initMap() { 
     var map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 4, 
      center: {lat: -24.345, lng: 134.46} 
     }); 

     var directionsService = new google.maps.DirectionsService; 
     var directionsDisplay = new google.maps.DirectionsRenderer({ 
      draggable: true, 
      map: map, 
     }); 

     var se = [ ["Telfer, WA", "Madura, WA"], 
        ["Newman, WA", "Zanthus, WA"], 
        ]; 

     for (i = 0; i < se.length; i++) { 
     directionsDisplay.addListener('directions_changed', function() { 
      computeTotalDistance(directionsDisplay.getDirections()); 
     }); 

     displayRoute(se[i][0], se[i][1], directionsService, 
      directionsDisplay); 
     } 

     } 


     function displayRoute(origin, destination, service, display) { 

      var waypo = []; 

      var wp = [ ["-26.170357", "126.535148"], 
        ["-23.715558", "133.889621"], 
        ["-20.719814", "139.486865"], 
        ["-30.877577", "143.568913"],     
        ]; 


     for (i = 0; i < wp.length; i++) { 
     waypo.push({ 
      location: new google.maps.LatLng(wp[i][0],wp[i][1]), 
      stopover: true 
     });} 


     service.route({ 
      origin: origin, 
      destination: destination, 
      waypoints: waypo, 
      travelMode: 'DRIVING', 
      avoidTolls: true 
     }, function(response, status) { 
      if (status === 'OK') { 
      display.setDirections(response); 
      } else { 
      alert('Could not display directions due to: ' + status); 
      } 
     }); 
     } 
+0

發佈代碼中只有一條路由。你怎麼試圖添加多個路線?你在尋找路線選擇嗎?那些不適用於航點。 – geocodezip

回答

0

要顯示多個路由,您需要在請求對象中將provideRouteAlternatives設置爲true。然後可以使用directionsRenderer對象來顯示路線。下面是一些這方面的示例代碼:

directionsService.route({ 
origin: "Houston, TX", 
destination: "Austin, TX", 
travelMode: 'DRIVING', 
provideRouteAlternatives: true 
}, function(response, status) { 
if (status === 'OK') { 
    for (var i = 0; i < response.routes.length; i++){ 
    var directionsDisplay = new google.maps.DirectionsRenderer; 
    if(i <= 0) 
     directionsDisplay.setOptions({ 
      polylineOptions: { 
          strokeColor: 'blue' 
          } 
     }); 
    else 
     directionsDisplay.setOptions({ 
      polylineOptions: { 
          strokeColor: 'red' 
          } 
     }); 
    directionsDisplay.setRouteIndex(i); 
    directionsDisplay.setDirections(response); 
    directionsDisplay.setMap(map); 
    } 
} else { 
    window.alert('Directions request failed due to ' + status); 
} 
}); 

我有這個證明上的jsfiddle這裏:

https://jsfiddle.net/Ly3xqqo4/1/

請注意,你需要插入自己的API密鑰才能使用小提琴。

我希望這有助於!