infowindow关闭和var(google maps api v3)

时间:2011-06-22 14:01:14

标签: javascript google-maps google-maps-api-3

在google maps api v.3中打开new时,我关闭了infowindow的问题。

var infowindow;
function addMarker(id, location) {
contentString = 'some content';

var marker = new google.maps.Marker({
  position: location,
  map: map
});

var infowindow = new google.maps.InfoWindow({
    content: contentString,
    maxWidth: 200
});

google.maps.event.addListener(marker, 'click', function() {
  if (infowindow) infowindow.close();  
  infowindow.open(map, marker); 
});

markersArray[id] = marker;
}

问题在于,在上面的代码中,旧的信息窗口在点击新信息时不会关闭,除非我从行 var infowindow = new google.maps.InfoWindow({<

删除 var / EM> 但是所有的信息都有相同的内容......

有任何帮助吗? 感谢。

1 个答案:

答案 0 :(得分:2)

使用全局变量来包含指向最后打开的标记的指针,并在打开新标记时关闭前一个标记。喜欢这个

//var infowindow; // <-- removed; should not be global
var openedInfoWindow = null;  // <-- added this here; make sure it's global

function addMarker(id, location) {
    contentString = 'some content';

    var marker = new google.maps.Marker({
        position: location,
        map: map
    });

    var infowindow = new google.maps.InfoWindow({
        content: contentString,
        maxWidth: 200
    });

    google.maps.event.addListener(marker, 'click', function() {
      if (openedInfoWindow != null) openedInfoWindow.close();  // <-- changed this
      infowindow.open(map, marker); 
      // added next 4 lines
      openedInfoWindow = infowindow;
      google.maps.event.addListener(infowindow, 'closeclick', function() {
          openedInfoWindow = null;
      });
    });

    markersArray[id] = marker;
}