2017-08-02 109 views
0

我有多个标记,并且当单击多个infoWindow时,其他已打开的infoWindows保持打开状态,混乱地图。我更喜欢它,如果我可以简单地重用一个infoWindow,移动它并更新它的内容。这是我在尝试下面的事情:Google地图 - 重复使用单个infoWindow获取多个标记

var info = new SnazzyInfoWindow(); 

     /* 
     * Loop through each item in the 'features' array, including info windows, and display the marker 
     */ 
     features.forEach(function (feature) { 
      var marker = new google.maps.Marker({ 
       position: feature.position, 
       icon: icons[feature.type].icon, 
       map: map 
      }); 

      var infoContent = feature.contentImage + feature.content; 

      marker.addListener('click', function() { 
       infoCallback(infoContent, marker); 
      }); 
     }); 

     function infoCallback(infoContent, marker) { 

      return function() { 
       info.close(); 
       info.setContent(infoContent) 
       info.open(map, marker); 
      }; 
     }; 

但是我收到错误Cannot read property 'placement' of undefined,似乎无法找出什么是错在这里。

请注意,我使用的是“Snazzy Info Window”插件,但我认为同样适用于股票信息窗口。

回答

1

是的。在onClick函数中,当marker.addListener('click')被执行时,你没有特征/标记,这些变量并不是它们在执行foreach时的样子。

我主要使用的一个技巧是使标记对象的数组中的onClick里你搜索数组中的“本”标记

事情是这样的:。!

var markers = []; // store the markers in this array 

features.forEach(function (feature) { 
    var marker = new google.maps.Marker({ 
    position: feature.position, 
    icon: icons[feature.type].icon, 
    map: map 
    }); 
    markers.push(marker); 

    marker.addListener('click', function() { 
    // first find out which marker was clicked on 
    var index = markers.indexOf(this); // this represents the marker that was clicked on 
    // index should be the same index as the index for features. 
    var feature = features[index]; 
    var marker = markers[index]; 
    var infoContent = feature.contentImage + feature.content; 
    // now we can call infoCallback. 
    infoCallback(infoContent, marker); 
    }); 
}); 
+0

完美,感谢 – wickywills

+0

非常漂亮的代码! –

相关问题