2012-09-24 64 views
0

我試圖編譯谷歌的示例代碼,並找出總距離,我相信腳本沒有錯..如果它是。谷歌的地圖不會被顯示......有一些東西丟失..任何一個可以請幫助..總計算不顯示

<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> 
    <script> 
     var directionDisplay; 
     var directionsService = new google.maps.DirectionsService(); 

     function initialize() { 
     directionsDisplay = new google.maps.DirectionsRenderer(); 
     var mapOptions = { 
      zoom: 7, 
      mapTypeId: google.maps.MapTypeId.ROADMAP, 
      center: new google.maps.LatLng(41.850033, -87.6500523) 
     }; 
     var map = new google.maps.Map(document.getElementById('map_canvas'), 
      mapOptions); 
     directionsDisplay.setMap(map); 
     directionsDisplay.setPanel(document.getElementById('directions-panel')); 

     var control = document.getElementById('control'); 
     control.style.display = 'block'; 
     map.controls[google.maps.ControlPosition.TOP].push(control); 
     } 

     function calcRoute() { 
     var start = document.getElementById('start').value; 
     var end = document.getElementById('end').value; 
     var request = { 
      origin: start, 
      destination: end, 
      travelMode: google.maps.DirectionsTravelMode.DRIVING 
     }; 
     directionsService.route(request, function(response, status) { 
      if (status == google.maps.DirectionsStatus.OK) { 
      directionsDisplay.setDirections(response); 
      } 
     }); 
     } 
     function computeTotalDistance(result) { 
     var total = 0; 
     var myroute = result.routes[0]; 
     for (i = 0; i < myroute.legs.length; i++) { 
     total += myroute.legs[i].distance.value; 
     } 
     total = total/1000. 
     document.getElementById("total").innerHTML = total + " km"; 
     } 


     google.maps.event.addDomListener(window, 'load', initialize); 
    </script> 
    </head> 
    <body> 
    <div id="control"> 
     <strong>Start:</strong> 
     <select id="start" onchange="calcRoute();"> 
     <option value="san bernardino, ca">San Bernardino</option> 
     <option value="los angeles, ca">Los Angeles</option> 
     </select> 
     <strong>End:</strong> 
     <select id="end" onchange="calcRoute();"> 
     <option value="san bernardino, ca">San Bernardino</option> 
     <option value="los angeles, ca">Los Angeles</option> 
     </select> 

    </div> 
    <div id="total"></div> 
    <div id="directions-panel"></div> 
    <div id="map_canvas"></div> 
    </body> 

回答

1

你永遠不打電話給你computeTotalDistance函數。您需要在DirectionsService.route回調函數中調用它。

 directionsService.route(request, function(response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
     directionsDisplay.setDirections(response); 
     computeTotalDistance(response); 
     } 

Working example

+0

它真的做到了爲我工作..非常感謝..非常感謝您的幫助.. –

1

嘗試

computeTotalDistance(response) 

而不是

computeTotalDistance(result)` 
+0

謝謝大衛..我也嘗試了第一個,它真的爲我工作..你剛纔提到的相同的解決方案..感謝任何方式很多關於你的幫助 –