2013-03-25 115 views
0

我有一張地圖,我希望將經緯度/緯度數據反饋推送到地圖數據數組。我有獲取數據的功能,但無法在地圖數據數組中使用該功能。如何動態地將數據添加到谷歌地圖API?

這個想法是當一個新的座標被添加到數組中時有一個新的標記放入。有任何想法嗎?提前致謝!

var ID='0'; 
     var DATA=[]; 
     function getData(){ 
      var url = 'http://us7.fieldagent.net/api/newResponses/'; 
      //url = 'http://us7.fieldagent.net/api/newResponses/; 
      $.post(url,{'id':ID},function(data){ 
       if(data.status_id == 0){ 
        ID = data.id; 
        console.log('Last Id: '+data.id); 
        var new_data = data.responses; 

        var count = 0 
        $.each(new_data,function(i,v){ 
         count += 1; 
         var coord = 'new google.maps.LatLng('+v.lat+','+v.lon+'),'; 
         DATA.push(coord); 
        }) 
        console.log('Added '+count+' responses..') 
       } 
      }); 
     } 
    $(document).ready(function(){ 
       getData(); 
       setInterval(getData,20*1000); 
      }); 

     function drop() { 
       for (var i = 0; i < DATA.length; i++) { 
         setTimeout(function() { 
          addMarker(); 
         }, i * 500); 
        } 
       } 

     function addMarker(){ 
      markers.push(new google.maps.Marker({ 
       position: DATA[iterator], 
       map: map, 
       draggable: false, 
       icon: 'fatie.svg', 
       animation: google.maps.Animation.DROP 
      })); 
      iterator++; 
     } 

回答

1

你需要實際的項目添加到地圖中。現在,你只需要添加一個項目到你的DATA陣列。您還需要使用新數據致電addMarker

您似乎希望將這些標記以一定的間隔添加到地圖中,以便隨着時間的推移將它們拖放到地圖上,同時還能夠從服務器查詢新的標記。

嘗試這樣的代碼:

var ID='0'; 
var DATA=[]; 
function getData(){ 
    var url = 'http://us7.fieldagent.net/api/newResponses/'; 
    $.post(url,{'id':ID},function(data){ 
     if(data.status_id == 0){ 
      ID = data.id; 
      console.log('Last Id: '+data.id); 
      var new_data = data.responses; 

      var count = 0 
      $.each(new_data,function(i,v){ 
       count += 1; 
       var coord = 'new google.maps.LatLng('+v.lat+','+v.lon+'),'; 
       DATA.push(coord); 
      }); 
      console.log('Added '+count+' responses..'); 
      if (count > 0) addMarker(); //call addMarker if there are new markers 
     } 
    }); 
} 
$(document).ready(function(){ 
    getData(); 
    setInterval(getData,20*1000); 
}); 

function addMarker(){ 
    if (DATA.length == 0) return; //exit if DATA is empty 
    markers.push(new google.maps.Marker({ 
     position: DATA.shift(), //take the first item in DATA 
     map: map, 
     draggable: false, 
     icon: 'fatie.svg', 
     animation: google.maps.Animation.DROP 
    })); 
    if (DATA.length > 0) setTimeout(addMarker, 500); //call again if needed 
} 
0

創建一個方法可以做兩件事。

  1. 添加到陣列
  2. 的項目添加到地圖
+0

1.這不就是DATA.push(座標);是在做? – astephenb 2013-03-25 21:19:40

+0

此外,函數'addMarker'將新的數據點添加到地圖。 當我有一個靜態數據數組時,addMarker和drop函數完美地工作。 – astephenb 2013-03-25 21:27:52

+0

你的DATA數組僅僅是一個帶座標的數組。要將它們添加到地圖中,您必須從數組中將它們添加並添加它們。這是一個單獨的步驟。僅僅因爲他們在陣列中不會讓他們出現在地圖上。我的方法:創建一個方法,它需要一個座標和a)將其添加到數組b)將其添加到地圖。而已。請參閱@jeffs解答一個稍微不同的答案。 – 2013-03-26 08:30:21

相關問題