0

我正在尝试使用以下代码生成多个 InfoWindows:编辑:为了澄清,我希望所有窗口同时打开。

    for (var i = 0; i < 3; i++) {
      var markerOptions = {position:point[i], map:map};
      var marker = new google.maps.Marker(markerOptions);
      content = "Hello " + i;
      infowindow[i] = new google.maps.InfoWindow({content: content}); 
      google.maps.event.addListener(marker, 'mouseover', function()
      {
        infowindow[i].open(map,this);   
      });
    }

(完整来源)

但是,我在 Chrome 中收到以下错误:Uncaught TypeError: Cannot call method 'open' of undefined。

当我使用普通变量“infowindow”而不是数组时,单个 infowindow 会按预期显示。

4

4 回答 4

1

您只能创建一个 infoWindow。我在这样的项目中使用过:

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

for (var i = 0; i < 3; i++) 
{
    var markerOptions = {position:point[i], map:map, html:'Hello' };
    var marker = new google.maps.Marker(markerOptions);

    google.maps.event.addListener(marker, 'mouseover', function()
    {
        infowindow.setContent(this.html); // this is the trick: html attribute on markerOptions :), I used a array here
        infowindow.open(map,this);   
    });
}
于 2012-04-09T20:14:02.043 回答
0

您是否将 infowindow[i] 输出到控制台(firebug)以查看它是否是您所期望的?我认为通常这样做的方法是生成一个 infowindow 对象并重用/移动和更改 infowindow 的内容。

这个链接可能很方便:http://www.svennerberg.com/2009/09/google-maps-api-3-infowindows/

于 2012-04-09T20:13:03.353 回答
0

工作样本

       var map;
      var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 2,
        mapTypeId: google.maps.MapTypeId.ROADMAP };
      var infowindow = new google.maps.InfoWindow();
      function initialize() {
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        point = [];
        point[0] = new google.maps.LatLng(0.0,0.0);
        point[1] = new google.maps.LatLng(0.0,10.0);
        point[2] = new google.maps.LatLng(0.0,20.0);


          for (var i = 0; i < 3; i++) {
                var content = "Hello"+i;
                addInfowindows(point[i], content )             
          }
      }
function addInfowindows(point, content){


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


          google.maps.event.addListener(marker, 'mouseover', function()
          {
            infowindow.setContent(content);
            infowindow.open(map,this);   
          });


}
 google.maps.event.addDomListener(window, 'load', initialize);
于 2012-04-09T20:13:47.523 回答
0

为了完成我想要的,我了解到需要一个闭包

for (var i = 0; i < 3; i++) 
{
  (function(i) {
    var markerOptions = {position:point[i], map:map, html:'Hello' };
    var marker = new google.maps.Marker(markerOptions);

    google.maps.event.addListener(marker, 'mouseover', function()
    {
        infowindow.setContent(this.html); // this is the trick: html attribute on markerOptions :), I used a array here
        infowindow.open(map,this);   
    });
  })(i);
}
于 2012-04-13T14:47:41.653 回答