2013-05-13 86 views
0

我有一個基於GPS的系統發送到MYSQL數據庫的座標。JQuery - 刷新標記位置(獲取移動)

使用此代碼:

(function() { 
    window.onload = function() { 

     // Creating a new map 
     var map = new google.maps.Map(document.getElementById("map"), { 
      center: new google.maps.LatLng(41.65, -0.88), 
      zoom: 1, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }); 

     function createPoints(json){ 
     var infoWindow = new google.maps.InfoWindow(); 

     // Looping through the JSON data 
     for (var i = 0, length = json.locations.length; i < length; i++) { 

       var data = json.locations[i], 
       latLng = new google.maps.LatLng(data.lat, data.long); 

      var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; 
      var marker = new google.maps.Marker({ 
       position: latLng, 
       map: map, 
       title: data.nome, 
       icon: iconBase + 'schools_maps.png' 
       }); 


      (function(marker, data) { 

       // Attaching a click event to the current marker 
       google.maps.event.addListener(marker, "click", function(e) { 
        infoWindow.setContent(data.nome); 
        infoWindow.open(map, marker); 
       }); 


      })(marker, data); 
         /* moveMarker(map, marker); */ 

     } 

     } 


     // Get the JSON data from PHP script 

var json ; 

$.getJSON("http://mywebservice/nmea_last.php").done(function(data) { 
    json = data; 
    createPoints(json); 
}); 

    } 

})(); 

UDING getJSON("http://mywebservice/nmea_last.php")一句,我得到的,全球定位系統發送(pediodically)到MySQL的最後一個座標,並標記正確顯示。我的問題是,我怎樣才能在地圖上進行動態刷新?

我想我需要使用setTimeout方法(或不?),但我不知道如何。任何幫助? 在此先感謝。

回答

1

我建議看setInterval函數,你可以用它來調用定期的功能。信息可以在here找到。

我相信你會想要在setInterval函數內包裝你的getJSON調用來拉新點並刷新地圖。這將是一個例子,它會每隔5秒觸發getJSON調用:

setInterval(function() { 
    $.getJSON("http://mywebservice/nmea_last.php").done(function(data) { 
    json = data; 
    createPoints(json); 
    }); 
}, 5000); 
+0

非常感謝!它似乎工作正常...只有一件事:我有多冷,刪除previouse標記? (實際上它堅持在地圖上) – doxsi 2013-05-13 17:07:31

+0

我自己無法想到具體的解決方案,但這可能會導致您朝着正確的方向發展:http://stackoverflow.com/questions/1544739/google-maps-api-v3-如何去除的,所有標誌物 – theaccordance 2013-05-13 18:44:26

1

嘗試改變的getJSON調用此:

setTimeout(function() { 
    $.getJSON("http://mywebservice/nmea_last.php").done(function(data) { 
     json = data; 
     createPoints(json); 
    }); 
}, 5000); 

5000表示5秒延遲,可以調整按你希望的屏幕刷新時間。

2

您可以使用AJAX拉來獲取座標每隔N毫秒:

var N = 1000; //every 1 second 
var timeout = function() { 
    setTimeout(function() 
    { 
    $.getJSON("http://mywebservice/nmea_last.php").done(function(data) { 
     json = data; 
     createPoints(json); 

     timeout(); //run again  
    }); 
    }, N); 
} 

timeout(); 
+0

謝謝!它似乎工作。 TheAccordance的解決方案也適用。在setInterval方面使用ajax有什麼優勢? – doxsi 2013-05-13 17:10:24

+0

@doxsi setInterval方法有一個基本流程。想象一下你的ajax請求需要5秒多一點的時間。在它完成之前,另一個Ajax被髮送......所以你同時有兩個Ajax請求。在setTimeout方法中,只有在當前ajax請求完成時才發送新的ajax請求 – 2013-05-14 05:04:30