2017-02-11 219 views
-3

我創建了一個腳本,它將從sql獲取緯度和經度,並在嵌入的谷歌地圖上放置一個標記,並且我希望每秒都能運行腳本,就像自動獲取數據和自動放置標記一樣。Javascript - 設置時間間隔

<script> 
    var infoWindow= null; 
    var map = null; 
    var markersArray = []; 


     function initMap() { 
      var myLatlng = new google.maps.LatLng(14.657971, 120.976970); 
      var map = new google.maps.Map(document.getElementById('map_canvas'), { 
      center: myLatlng, 
      zoom: 16, 
      streetViewControl : false, 
      mapTypeId : google.maps.MapTypeId.HYBRID, 
     }); 

     var infoWindow = new google.maps.InfoWindow; 

     updateMaps(); 

function updateMaps() { 


     // Change this depending on the name of your PHP or XML file 

     downloadUrl('phpsqlajax_genxml.php?t=', function(data) { 
      var xml = data.responseXML; 
      var markers = xml.documentElement.getElementsByTagName('marker'); 
      Array.prototype.forEach.call(markers, function(markerElem) { 
       var name = markerElem.getAttribute('name'); 
       var address = markerElem.getAttribute('address'); 
       var type = markerElem.getAttribute('type'); 

       var point = new google.maps.LatLng(
        parseFloat(markerElem.getAttribute('lat')), 
        parseFloat(markerElem.getAttribute('lng'))); 

       var infowincontent = document.createElement('div'); 
       var strong = document.createElement('strong'); 
       strong.textContent = name 
       infowincontent.appendChild(strong); 
       infowincontent.appendChild(document.createElement('br')); 

       var text = document.createElement('text'); 
       text.textContent = address 
       infowincontent.appendChild(text); 
       var icon = customLabel[type] || {}; 
       var marker = new google.maps.Marker({ 
       map: map, 
       position: point, 
       label: icon.label 

       }); 


       marker.addListener('click', function() { 
       infoWindow.setContent(infowincontent); 
       infoWindow.open(map, marker); 

       }); 
      }); 
      }); 
     } 


     function downloadUrl(url, callback) { 
     var request = window.ActiveXObject ? 
      new ActiveXObject('Microsoft.XMLHTTP') : 
      new XMLHttpRequest; 

     request.onreadystatechange = function() { 
      if (request.readyState == 4) { 
      request.onreadystatechange = doNothing; 
      callback(request, request.status); 
      } 
     }; 

     request.open('GET', url, true); 
     request.send(null); 
     } 

     function doNothing() {} 

     } 
     window.setInterval(updateMaps, 1000);  
    </script> 
+1

有什麼問題? – Daniel

+1

歡迎使用堆棧溢出。請閱讀[問]並實際提供一個**問題**供我們回答。 –

+2

好嗎?顯然你知道'setInterval'可以幫助你做到這一點,那麼問題是什麼? – Carcigenicate

回答

0
var update; 

function updateInterval() { 
    update = setInterval(function() { 
    updateMaps() 
    }, 1000); 
} 
updateInterval(); 

你必須使用jQuery加載updateInterval()時,該文件已準備就緒或在身體的最後寫<script>updateInterval();</script>

+0

您必須在函數名稱後面添加'()'以便調用它,或者只需使用函數名稱作爲第一個參數,而不是將其封裝在匿名函數中 – Connum

+0

您是對的,謝謝! –