InfoWindow - Google地图API

时间:2012-05-25 03:38:18

标签: javascript google-maps

我尝试为所有标记添加infowindows。但是我只为最后一个标记添加了一个InfoWindow。 你能救我吗?

for (i = 0; i < events.length; i++) {
    var contentString = '<div id="content">'+i+'bla-bla-bla</div>';
    var infowindow = new google.maps.InfoWindow({
       content: contentString
    });
    var newMarker = new google.maps.Marker({
       position: new google.maps.LatLng(events[i][1], events[i][2]),
       map: map,
       title: events[i][0]
     });
     newMarker.categorysassasas = 2;
     newMarker.category = events[i][3];
     markers.push(newMarker);
     google.maps.event.addListener(newMarker, 'click', function() {
        infowindow.open(map,newMarker);
     });
}

1 个答案:

答案 0 :(得分:-1)

在此stackoverflow中找到了与您的问题类似的解决方案:Trying to bind multiple InfoWindows to multiple Markers on a Google Map and failing

基本上你要做的就是将你的addlistener函数包装在另一个函数中,为你的标记变量创建一个闭包 - 这样它就被绑定到了infowindow。在你的情况下,我相信你必须在init()之外添加listenMarker函数,并传递marker和infowindow的变量,就像这样..

function listenMarker (marker, info)
{
  // so marker is associated with the closure created for the listenMarker function call
  google.maps.event.addListener(marker, 'click', function() {
    info.open(map, marker);
  });
}

然后在你调用addlistener事件的for循环中,将其替换为:

listenMarker(newMarker, infowindow);

这应该可以解决问题。

相关问题