我们使用infowindow的多个标记。一切都很好。 问题是当我们点击标记时,infowindow会打开但是在点击其他标记时它不会关闭。它保持开放。所以可以为这个问题提供解决方案。
var berlin = new google.maps.LatLng(52.520816, 13.410186);
var neighborhoods = [
new google.maps.LatLng(52.511467, 13.447179),
new google.maps.LatLng(52.549061, 13.422975),
new google.maps.LatLng(52.497622, 13.396110),
new google.maps.LatLng(52.517683, 13.394393)
];
var markers = [];
var iterator = 0;
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: berlin
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function drop() {
for (var i = 0; i < neighborhoods.length; i++) {
setTimeout(function() {
addMarker();
}, i * 200);
}
}
function addMarker() {
var marker = new google.maps.Marker({
position: neighborhoods[iterator],
map: map,
draggable: false
});
markers.push(marker);
var contentString = $("#pop"+iterator).html();
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 300,
maxHeight: 500
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
iterator++;
}
答案 0 :(得分:4)
您正在创建尽可能多的infowindow
s,因为有标记。在你的情况下,我认为一个infowindow
就足够了。因此,对于仅使用一个infowindow
,您可以在全局范围内实现此目的:
//Using lazy initialization.
//InfoWindow will be created only after the first call
var getInfoWindow = (function(){
var _instance = null;
return function(){
if(_instance == null){
_instance = new google.maps.InfoWindow({
maxWidth: 300,
maxHeight: 500
});
}
return _instance;
};
})();
此外,您需要为每个必须在点击事件上显示的标记存储contentString
。所以addMarker
方法的最终修改将是这样的:
function addMarker() {
var marker = new google.maps.Marker({
position: neighborhoods[iterator],
map: map,
draggable: false
});
markers.push(marker);
//Storing content html
marker.contentString = $("#pop"+iterator).html();
google.maps.event.addListener(marker, 'click', function() {
//Setting content of InfoWindow
getInfoWindow().setContent( marker.contentString );
//Opening
getInfoWindow().open(map,marker);
});
iterator++;
}
答案 1 :(得分:1)
将var infowindow放在addMarker函数之外。像这样:
var infowindow = new google.maps.InfoWindow();
然后在你的addMarker函数中使用
infowindow.setContent(contentString);
这样,infowindow只创建一次。单击不同的标记只会移动窗口并设置内容。