![](/img/trans.png)
[英]Auto close InfoWindow Google Maps API when click another marker
[英]Could I make Infowindow in Google maps API dissapear when mouse out of marker, but not dissapear when mouse move from marker to him infowindow
在JS中,當我將鼠標移出標記時,需要關閉標記上的Infowindow,但是當鼠標懸停在infowindow上時,infowindow不應消失。 因為如果在信息窗口中有滾動,則用戶可以滾動它(我想這樣)。
google.maps.event.addListener(marker, 'mouseover', (function (marker, content, infowindow) {
return function () {
if (content != null && content != "")
{
infowindow.setContent(content);
infowindow.open(map, marker);
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else { marker.setAnimation(google.maps.Animation.BOUNCE);
console.log(content);
}
}
};
})(marker, content, infowindow));
google.maps.event.addListener(marker, 'mouseout', (function (marker, infowindow) {
return function () {
infowindow.close(map, marker);
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
}
};
})(marker, infowindow));
問題 :當鼠標離開標記時,信息窗口立即關閉。 如果用戶要滾動查看信息窗口上的任何內容,則無法將鼠標從標記移到信息窗口。
解決方案 :在關閉信息窗口之前創建一個小的延遲。 這使用戶有時間將鼠標從標記移到信息窗口。
marker.addListener('mouseout', function() {
timeoutID = setTimeout(function() {
if (!mouseOverInfoWindow) {
closeInfoWindow();
}
}, 400);
});
延遲之后,如果鼠標沒有懸停在信息窗口上,請將其關閉。 如果它懸停在信息窗口上,請不要執行任何操作。
如果查看InfoWindow類參考的Events部分,您將看到信息窗口沒有像標記一樣的mouseout
事件。
因此,為了在用戶的鼠標移開時關閉信息窗口,您需要獲取對DOM上信息窗口元素的引用,並向其添加mouseout
事件偵聽器。
var infoWindowElement = document.querySelector('.gm-style .gm-style-iw');
infoWindowElement.addEventListener('mouseout', function() {
closeInfoWindow();
mouseOverInfoWindow = false;
});
請記住,打開事件偵聽器后只能將其添加到信息窗口DOM元素中,因為打開它會將其添加到DOM中。 如下代碼所示:
function openInfoWindow(marker) {
infoWindow.open(map, marker);
addOpenInfoWindowListeners();
}
我首先打開信息窗口(將其添加到DOM),然后添加偵聽器。
這是帶有地圖的更新的JSBin ,其中顯示了一些標記,這些標記的信息窗口具有所需的功能。 我要做的就是遍歷數據,並為每個項目創建一個標記和事件偵聽器。
markerData.forEach(function(item) {
var marker = new google.maps.Marker({
position: item.position,
map: map
});
addMarkerListeners(marker, item.infoWindowContent);
})
我還將addOpenInfoWindowListeners
方法更新為:
function addOpenInfoWindowListeners() {
var infoWindowElement = document.querySelector('.gm-style .gm-style-iw').parentNode;
infoWindowElement.addEventListener('mouseleave', function() {
closeInfoWindow();
mouseOverInfoWindow = false;
});
infoWindowElement.addEventListener('mouseenter', function() {
mouseOverInfoWindow = true;
});
}
現在,我以.gm-style .gm-style-iw
的parentNode
為目標,並監聽mouseleave
和mouseenter
事件(與mouseout
和mouseover
相反)。 這樣可使懸停功能適用於沒有可滾動內容的信息窗口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.