2015-09-26 95 views
2

我對於在我的地圖中爲每個標記分配infowindow存在問題。爲谷歌地圖中的每個標記分配infowindow

JS代碼:

for (i=0;i<location.length;i++){ 
    var id = location[i][0]; 
    var name = location [i][1]; 
    var pos = new google.maps.LatLng(location[i[3],location[i][4]); 


    var contentString = id; 
    var infowindow = new google.maps.InfoWindow({content:contentString}); 
    var marker= new google.maps.Marker({position: pos, map: map, title: id}); 

    marker.addListener('click', function() { infowindow.open(map, this); 

});

問題是我的點擊處理程序會爲每個標記顯示相同的「id」(id顯示的是我的數據庫中最後一條記錄的id)。 有沒有辦法顯示每個標記的每個infowindow?

+2

[谷歌地圖JS API V3 - 簡單多個標記的例子]可能的複製(http://stackoverflow.com/questions/3059044/google-maps-js-api -v3-simple-multiple-marker-example) – geocodezip

回答

11

假設你位置陣列被取出,並從數據庫填充...

首先你有一個錯誤:

var pos = new google.maps.LatLng(location[i[3],location[i][4]);

你應該解決您的括號,並把它這種方式:

var pos = new google.maps.LatLng(location[ i ][3],location[ i ][4]);

下面是一個例子:

我試圖按照你的榜樣,就像我能因爲你沒有指定一個數組,並取得一個對應於您的陣列(你可以,如果你想添加一個列的名稱)

循環:

在循環之前
for (var i = 0; i < location.length; i++) { 

    var marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(location[i][1], location[i][2]), 
     map: map, 
     title: location[i][0] 
    }); 

    google.maps.event.addListener(marker, 'click', (function(marker, i) { 
     return function() { 
      infowindow.setContent(location[i][0]); 
      infowindow.open(map, marker); 
     } 
    })(marker, i)); 
} 

聲明你的信息窗口,並提取它的事件中

信息窗口:

var infowindow = new google.maps.InfoWindow(); 

Click事件:

google.maps.event.addListener(marker, 'click', (function(marker, i) { 
    return function() { 
     infowindow.setContent(location[i][0]); 
     infowindow.open(map, marker); 
    } 
})(marker, i)); 

完全小提琴例如:http://jsfiddle.net/eugensunic/7TZFP/5/

+1

太棒了!謝謝你的提琴 – Ruby

+1

謝謝。添加'(函數(marker,i)'和'return function(){...}'使得我的工作成功,沒有它不起作用,我真的不明白爲什麼 – Valachio

+0

看看閉包JavaScript的... –