2017-08-02 110 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

非常漂亮的代碼! –

相關問題