2015-06-22 44 views
-1

我試圖插入一個谷歌地圖,多個標記,將它們添加到一個循環的地圖中;問題是我有一個函數在infoWindow()標記,但如果我嘗試只有兩個位置,被調用的函數在這兩個標記,但只有最後一個值,換句話說,該功能將剛剛過去的parameters.Here的代碼如何在一個循環中創建多個標記內插入函數

var luoghi = {"city":[ 
    { "lat":"45.46" , "lng":"9.19" , "name":"Milano" }, 
    { "lat":"41.12" , "lng":"16.86" , "name":"Bari" } 
]} ; 

var marker2,i;   
    for(i in luoghi.city){ 
     lat = luoghi.city[i].lat; 
     lng= luoghi.city[i].lng; 
     var myLatlng = new google.maps.LatLng(lat,lng); 

     marker2 = new google.maps.Marker({ 
      position: myLatlng, 
      map: map, 
      animation: google.maps.Animation.DROP, 
      title: ''+myLatlng 
     }); 

     google.maps.event.addListener(marker2,'click',(function(marker2){ 
      return function(){ 
       if(infoWindow) infoWindow.close(); 
       var contentString = '<p>Visiona meteo e foto utenti flickr in questa zona</p>'+ 
            '<input type= "button" value="Visualizza" onclick="visualizza()">'; 
       infoWindow = new google.maps.InfoWindow({ 
        content: contentString 
       }); 
       infoWindow.open(map,marker2); 
     } 
    })(marker2)); 
} 

功能visualizza()是正確的,問題出在循環中,我無法弄清楚它爲什麼不能像我期望的那樣工作。提前致謝 !

+0

你需要使用閉包檢查這個問題,http://stackoverflow.com/questions/30941294/how-to-call-unique-function-for-dynamically-created-checkboxes-in- a-div/30941571#30941571 –

+0

你能寫一下我怎麼做才能讓這段代碼以正確的方式運行嗎?我無法解決它@tao – Mirko

回答

0

您有範圍問題。試試這個:

var luoghi = {"city":[ 
    { "lat":"45.46" , "lng":"9.19" , "name":"Milano" }, 
    { "lat":"41.12" , "lng":"16.86" , "name":"Bari" } 
]} ; 

var marker = {}; 
var infoWindow = {}; 

for(var i in luoghi.city){ 
    var lat = luoghi.city[i].lat; 
    var lng= luoghi.city[i].lng; 
    var myLatlng = new google.maps.LatLng(lat,lng); 

    marker[i] = new google.maps.Marker({ 
     position: myLatlng, 
     map: map, 
     animation: google.maps.Animation.DROP, 
     title: ''+myLatlng 
    }); 

    infoWindow[i] = new google.maps.InfoWindow({ 
     content: '<p>Visiona meteo e foto utenti flickr in questa zona</p><input type= "button" value="Visualizza" onclick="visualizza()">' 
    }); 

    google.maps.event.addListener(marker[i], 'click', function(marker){ 
     infoWindow.open(map, marker); 
    }(marker[i])); 
} 
+0

通過這種方式代碼不起作用,它只在地圖上放置一個標記(Milano),並且不會彈出infoWindow @Thibault – Mirko

相關問題