2013-07-09 133 views
1

射擊多個JavaScript函數我已經成功地創建一個簡單的地圖有2個目的地之間存在顯着的路線。此外,我需要拉距離值,然後做一些基本的數學運算(乘以2)。它一切正常,但不是頁面加載。更準確地說,地圖將顯示在頁面加載和距離,但距離值不被拉出,它不會被乘以2。我設法使其在移動鼠標的工作,但它不是完美的替代品。在頁面加載

下面是代碼:

<head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> 
    <meta charset="utf-8"> 
    <title>Directions</title> 
    <link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet"> 
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&region=US"></script> 
    <script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script> 
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script> 
    <script src="http://www.pengoworks.com/workshop/jquery/calculation/jquery.calculation.min.js" type="text/javascript"></script> 
    <script> 
     $(document).ready(function() { 

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

      function initialize() { 

       var mapOptions = { 
        zoom: 7, 
        mapTypeId: google.maps.MapTypeId.ROADMAP, 
       }; 
       map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 
       directionsDisplay.setMap(map); 
       directionsDisplay.setPanel(document.getElementById('directionsPanel')); 

       google.maps.event.addListener(directionsDisplay, 'directions_changed', function() { 
        computeTotalDistance(directionsDisplay.directions); 
       }); 

       calcRoute(); 
      } 

      function calcRoute() { 

       var request = { 
        origin: 'Houston', 
        destination: 'Dallas', 
        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 (var 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); 


      function stripint() { 
       var val = $('[jsdisplay=distance]').text(); // get text content of <span jstcache="7"> 

       // Replace using regex instead of strings, to catch more than the first match 
       val = val.replace(/\./g, ""); 
       val = val.replace(/,/g, "."); 
       val = val.replace(/_/g, ","); 

       $('#dist').val(val); 
      } 

      function recalc() { 

       $("[id^='total_price_ht']").calc(
       // the equation to use for the calculation 
       "di * 10", { 
        bind: "keyup", 
        di: $("[id^='dist']") 
       }, function(s) { 
        // return the number as a dollar amount 
        return "$" + s.toFixed(2); 
       }); 
      } 

      $('#content').mousemove(function() { 
       stripint(); 
       recalc(); 
      }); 

      stripint(); 
      recalc(); 
     }); 
    </script> 
</head> 

<body> 
    <div id="content"> 
     <p>Distance: <span id="total"></span> 

     </p> 
     <input type="text" value="0" name="dist" id="dist" /> 
     <div id="total_price_ht_0" class="price">$0.00</div> 
     <div id="map-canvas" style="width:100%; height:500px"></div> 
     <div id="directionsPanel" style="width:100%; height:auto"></div> 
    </div> 
</body> 

回答

2

首先你不需要使用$(document).ready(),因爲你已經初始化功能綁定到窗口onLoad事件google.maps.event.addDomListener(window, 'load', initialize);

你想要的是等到方向和距離計算,你真的不中需要從directionsPanel中讀取它,你可以直接從API響應中讀取任何你需要的東西。

使用回調calcRoute這樣的:

directionsService.route(request, function(response, status) { 
    if (status == google.maps.DirectionsStatus.OK) { 
    directionsDisplay.setDirections(response); 
    dist = response.routes[0].legs[0].distance.text; 
    stripint(dist); 
    recalc(); 
    } 
}); 

,你還需要將DIST參數添加到您strprint

function stripint(val) { 

    // Replace using regex instead of strings, to catch more than the first match 
    val = val.replace(/\./g, ""); 
    val = val.replace(/,/g, "."); 
    val = val.replace(/_/g, ","); 

    $('#dist').val(val); 
} 

因此新的代碼不使用的document.ready和在API響應時立即計算價格。

<script>標籤:

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

function initialize() { 

    var mapOptions = { 
     zoom: 7, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
    }; 
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 
    directionsDisplay.setMap(map); 
    directionsDisplay.setPanel(document.getElementById('directionsPanel')); 

    google.maps.event.addListener(directionsDisplay, 'directions_changed', function() { 
     computeTotalDistance(directionsDisplay.directions); 
    }); 

    calcRoute(); 
} 

function calcRoute() { 

    var request = { 
     origin: 'Houston', 
     destination: 'Dallas', 
     travelMode: google.maps.DirectionsTravelMode.DRIVING 
    }; 
    directionsService.route(request, function (response, status) { 
     if (status == google.maps.DirectionsStatus.OK) { 
      directionsDisplay.setDirections(response); 
      dist = response.routes[0].legs[0].distance.text; 
      stripint(dist); 
      recalc(); 
     } 
    }); 
} 

function computeTotalDistance(result) { 
    var total = 0; 
    var myroute = result.routes[0]; 
    for (var 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); 


function stripint(val) { 

    // Replace using regex instead of strings, to catch more than the first match 
    val = val.replace(/\./g, ""); 
    val = val.replace(/,/g, "."); 
    val = val.replace(/_/g, ","); 

    $('#dist').val(val); 
} 

function recalc() { 

    $("[id^='total_price_ht']").calc(
     // the equation to use for the calculation 
     "di * 10", { 
      bind: "keyup", 
      di: $("[id^='dist']") 
     }, function (s) { 
      // return the number as a dollar amount 
      return "$" + s.toFixed(2); 
     }); 
} 
+1

我想上傳的內容:兩個'directionsService.route'(一個Ajax變相收費)和'directionsDisplay.setDirections'似乎是異步的。出於這個原因,如果你不會檢索來自AJAX請求,其中'stripint(DIST)的「總距離」;'現在,而是試圖從'$的距離(「[jsdisplay =距離]」)' ,你會發現在那一點距離還沒有到那個領域。 – Sumurai8

+0

@barvaz謝謝barvaz,那就是我一直在尋找的! – take2

-1

我認爲你是在這裏失去了document.ready()

+0

我究竟應該如何實現它在這種情況下?我試圖將最後一個腳本更改爲'',但它不會改變任何東西。 – take2

+0

$(文件)。就緒(函數(){ //此處插入功能 }); – aakashkrgoel

+0

-1 @aakashkrgoel:通過檢查代碼,你可以看到這不會奏效。不是-every-問題可以通過簡單地將'document.ready()'包裝在它周圍來解決,這就是其中之一。 – Sumurai8

0

這裏是沒有必要有兩個標籤;你可以把一切都放在一個裏面。您的一些功能使用jQuery選擇,儘量把所有的人都在$(文件)。就緒(內),這將保證所有選定的元素都可以通過他們被稱爲時間:

$(document).ready(function(){ 

    //Insert your functions with selectors here 

}); 

這裏是裏面的東西的document.ready重排後的代碼:http://jsbin.com/iqejiy/1/edit

希望它能幫助。

+0

這可能會起作用,但我錯過了把它放在哪裏。我設置了一個小提琴(http://jsfiddle.net/rbnUU/),雖然由於某種原因它不會顯示地圖。在結束標籤之前,它在哪裏? ('') – take2

+0

@ take2 $(document).ready(function(){});內的任何內容都可以放在調用jquery庫之後的任何地方。在''標籤之前放置對jQuery庫和代碼的調用會更好。'.ready()'方法確保頁面已經被加載。 – hitautodestruct

+0

我更新了小提琴:http://jsfiddle.net/rbnUU/3/。我在瀏覽器上測試過,沒有錯誤;現在你必須檢查你的功能是否像你想要的那樣工作。我會在之前放置所有

  • 11. 添加在頁面加載
  • 12. 加載頁面
  • 13. 頁面加載
  • 14. 頁面加載
  • 15. 頁面加載
  • 16. 頁面加載
  • 17. 頁面加載
  • 18. 頁面加載
  • 19. 加載頁面
  • 20. 頁面加載
  • 21. 加載頁面
  • 22. 在已加載的jquery頁面中加載頁面!
  • 23. jquery .get頁面加載不加載在頁面頂部
  • 24. 在jQueryMobile上加載並執行audio.js頁面加載AJAX頁面
  • 25. 在頁面加載後立即再次加載頁面
  • 26. 如何在頁面完全加載後加載PHP頁面?
  • 27. 如何在加載父頁面之前加載子頁面?
  • 28. 在滾動頁面加載更多不加載頁面2
  • 29. 在AJAX加載頁面上強制加載頁面
  • 30. 加載內容在頁面加載