多个 Google 具有延迟内容的地图信息窗口

Multiple Google Maps InfoWindows with deferred content

我在处理多个 Google 地图 (JS API v3) InfoWindows 一个接一个附加到多个标记的内容时遇到一些问题。

问题似乎与以下事实有关:我将打开 InfoWindow 的时间推迟到我完成从最终将填充它的服务器检索其内容的那一刻。

结果是,在关闭那个 InfoWindow 并重新打开它时,它被重新绘制的次数与我单击其标记的次数一样多。


显示代码之前的示例:

一旦正确初始化了 GMaps 并设置了标记,我单击其中之一,它的相关信息窗口就会出现。

然后我关闭它。

我点击同一个标记,出现了两个重叠的信息窗口(或者可能是一个,但打开了两次)。

然后我将其关闭(并且应该关闭了两个 InfoWindows)。

依此类推。

这是代码

 var pins = {
     list: [], // where the markers objects are stored.
     window: new google.maps.InfoWindow({
                 content: "Loading..." // promised content
             }),
     draw: function(coords, content_id, timeout) {
               setTimeout(function() {
                   pins.list.push(new google.maps.Marker({
                       position: coords,
                       map: map, // initialized elsewhere
                       title: content_id
                   });
               });
           },
     drop: function(array_of_pins) { // array of objects, each one containing
                                     // "coords" and "content_id" respectively
                                     // of the marker and the InfoWindow.
                var timeout = 100;

                for (i in pins.list) // Loop added to solve the problem
                    google.maps.event.clearListeners(pins.list[i], "click");

                for (i in array_of_pins)
                     pins.draw( array_of_pins[i].coords,
                                array_of_pins[i].content_id, 
                                i * timeout );

                setTimeout(function() {
                    for (i in pins.list) 
                         google.maps.event.addListener(
                             pins.list[i],
                             "click",
                             function() { 
                                 pins.content(this, this.title);
                             }
                         );
                }, array_of_pins.length * timeout);
           },
     content: function(marker, content_id) {
               deferredContentFunction(content_id)
                       .done(function(data) {
                           var content = '<p>'+data.content+'</p>';
                           pins.window.setContent(content);
                           pins.window.open(map, marker);
                       })
                       .fail(function() {
                           // error handling
                       });
           }
 };

我怀疑 pins.drop() 函数中对相关标记的引用(通过 this)在某些时候丢失了,这反过来又导致了问题。

您多次将点击侦听器添加到标记(每次在引脚数组上调用 drop 一次)。

一个选项是在再次添加之前清除监听器:

for (i in pins.list) 
  google.maps.event.clearListeners(pins.list[i], "click");
  google.maps.event.addListener(
    pins.list[i],
    "click",
    function() { 
      pins.content(this, this.title);
    }
  );