谷歌地图 - 重复单个infoWindow用于多个标记

时间:2017-08-02 08:08:51

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

我有多个标记,目前当点击多个infoWindow时,另一个已打开的infoWindows保持打开状态,使地图混乱。如果我可以简单地重复使用一个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"插件,但我认为同样适用于股票infoWindow。

1 个答案:

答案 0 :(得分:2)

是。在onClick函数中,当marker.addListener('点击'正在执行时,你没有功能/标记。变量不是foreach执行时的变量。

我主要使用的一个技巧是制作标记对象的数组。在onClick中搜索' this'数组内的标记。

这样的事情:

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);
  });
});