【问题标题】:close other infowindows nicely很好地关闭其他信息窗口
【发布时间】:2011-02-25 07:23:33
【问题描述】:

我目前这样做是为了为我的谷歌地图创建标记。

function createMarker(posn, title, html) {
            var marker = new google.maps.Marker({ position: posn, title: title, draggable: false });
            marker['infowindow'] = new google.maps.InfoWindow({ content: html });

            infoWindows.push(marker['infowindow']);
            google.maps.event.addListener(marker, "click", function () {
                for (i = 0; i < infoWindows.length; i++) {
                    infoWindows[i].close();
                }
                this['infowindow'].open(map, this);
            });
            return marker;
        }

我对 for 循环不满意,为了关闭标记,我知道可以通过使用一个引用来完成类似的事情:

if (infowindow) infowindow.close();

我使用上述代码的原因是因为我正在做类似
markers[myPoint]['infowindow'].open(map, markers[myPoint]); else where(myPoint 是一个数字)之类的事情。

我怎样才能避免这个 for 循环来关闭打开的 infowindows 并以很好的方式做到这一点?

【问题讨论】:

    标签: javascript google-maps


    【解决方案1】:

    只需将上次打开的 infoWindow 存储在全局变量中:

    var activeInfoWindow;
    
    function createMarker(posn, title, html) {
        var marker = new google.maps.Marker({ position: posn, title: title, draggable: false });
        marker['infowindow'] = new google.maps.InfoWindow({ content: html });
    
        infoWindows.push(marker['infowindow']);
        google.maps.event.addListener(marker, "click", function () {
            if ( activeInfoWindow == this['infowindow'] ) {
                return;
            }
            if ( activeInfoWindow ) {
                activeInfoWindow.close();
            }
    
            this['infowindow'].open(map, this);
            activeInfoWindow = this['infowindow'];
        });
        return marker;
    }
    

    【讨论】:

    • 在单击标记时出现错误,然后单击其信息窗口上的关闭按钮,然后再次单击该标记。它不会再显示信息窗口。要解决此问题,请删除 if ( activeInfoWindow == this['infowindow'] ) { return;}
    【解决方案2】:

    另一种方法是只有一个 InfoWindow,然后在标记单击事件上调用 InfoWindow 的 setContent 属性,然后调用带有地图和标记作为参数的 open 事件。

    我发现这种方法在我的应用程序中更好,我在地图上有 10,000 多个标记。

    见:http://code.google.com/apis/maps/documentation/javascript/reference.html#InfoWindow

    infoWindow = new google.maps.InfoWindow();
    
    function createMarker(posn, title, html) {
        var marker = new google.maps.Marker({ position: posn, title: title, draggable: false });
        marker['content'] = html;
        google.maps.event.addListener(marker, "click", function () {
            infoWindow.setContent(this['content']);
            infoWindow.open(map, this);
        });
        return marker;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2013-02-21
      • 1970-01-01
      • 2015-02-11
      • 2023-01-24
      • 2014-04-18
      相关资源
      最近更新 更多