2017-02-11 251 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

您是对的,谢谢! –