点击谷歌地图上的标记显示所有人的相同文本

时间:2014-03-08 22:33:23

标签: javascript google-maps

我连接到数据库并获取一些信息作为json然后我显示它们当我这样做它可以轻松识别lan和longtitude并在地图上显示它们但是当涉及到文本时我返回以显示它在用户点击标记只显示一个文本,似乎它将文本附加到第一个标记,所有其他标记附加相同的文本我错过了什么?我完全糊涂了!

for (var i=0; i<tweetsToPlot.length; i++){
        var lat = tweetsToPlot[i].lat;
        var lng = tweetsToPlot[i].lng;
        var myLatLng = new google.maps.LatLng(lat, lng);
        var txt=tweetsToPlot[i].text;
         var myMarker = new google.maps.Marker({
              position: myLatLng,
              title: "LatLng Feb 17",
              map:map
             }); 

        google.maps.event.addListener(myMarker, 'click', function() {
            var infowindow = new google.maps.InfoWindow({
              content: txt
            });
            infowindow.open(map, this);
          });

        var index = tweetsToPlot[i].id;
        discs[index] = myMarker;
       myMarker.setVisible(true);   
    }
}

1 个答案:

答案 0 :(得分:0)

你需要关闭。您的myMarker变量会不断变化,因此即使您已将点击处理程序分配给标记,当您遍历循环时,标记的实际参考也会不断变化。

......至少,这听起来像是什么(和症状匹配)。

(function(markerObj) {
    google.maps.event.addListener(myMarker, 'click', function() {
        var infowindow = new google.maps.InfoWindow({
            content: txt
        });
        infowindow.open(map, this);
    });
})(myMarker);