2017-03-04 10 views
1

これは私のコードです。私はマップに複数のルートが表示されるようにしています。私はそのために複数のオブジェクトが必要だと聞きましたが、実際にはどのように行うのかわかりません。誰か助けてくれますか?Googleマップ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

投稿コードには1つのルートしかありません。どのように複数のルートを追加しようとしていますか?あなたはルートの代替案をお探しですか?ウェイポイントでは機能しません。 – 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キーを挿入する必要がありますのでご了承ください。

こちらがお役に立てば幸いです。

関連する問題