创建我的 Google map markers, 时
我正在像这样添加事件监听器 -
var infowindow = new google.maps.InfoWindow({
content: 'Hi there from Alabama!'
});
google.maps.event.addListener(marker, 'mouseover', function () {
infowindow.open(map, marker); // this displays the infowindow on mouseover
});
google.maps.event.addListener(marker, 'mouseout', function () {
infowindow.close(); // this close the infowindow on mouseout
});
marker.addListener('click', function () {
google.maps.event.clearListeners(marker, 'mouseout');
// this removes the mouseout listener when the marker is clicked so that it stays
// present after mouseout.
});
前面提到的工作很好,但我也希望能够在信息窗口关闭后重新添加 mouseout
事件。
我尝试将其添加到我的函数中 -
google.maps.event.addListener(infowindow, 'closeclick', function () {
google.maps.event.addListener(marker, 'mouseout');
// when the info window is closed the mouseout event is reinstated
// I also previously added an alert here to make sure it was hit!
});
这可以创建标记,但实际上,我可以单击标记 > mouseout 并使信息窗口保持存在状态 > 关闭信息窗口。所有需要的行为。
然而,再次将鼠标悬停在标记上时,信息窗口会显示(如预期的那样),但在点击 mouseout
事件时,我得到 -
JavaScript runtime error: Unable to get property 'apply' of undefined or null reference
错误存在于 Google api JS 文件中,因此很难确定问题的根源。如何在 infowindow
关闭时正确恢复 mouseout
事件?
最佳答案
目前,您在事件分配中有一个匿名函数:
google.maps.event.addListener(marker, 'mouseout', function () {
infowindow.close(); // this close the infowindow on mouseout
});
如果你创建一个命名函数,你可以像这样添加它:
function mouseoutHandler() {
infowindow.close(); // this close the infowindow on mouseout
}
google.maps.event.addListener(marker, 'mouseout', mouseoutHandler);
然后,你可以删除它...
marker.addListener('click', function () {
google.maps.event.clearListeners(marker, 'mouseout');
// this removes the mouseout listener when the marker is clicked so that it stays
// present after mouseout.
});
稍后,您只需像第一次一样重新添加事件 -- 因为您有一个命名函数,所以您不会丢失声明!
如果您在删除原始事件时仍然遇到错误,您 might try being more specific :
var listenerHandle = google.maps.event.addListener(marker, 'mouseout', mouseoutHandler);
// later...
google.maps.event.removeListener(listenerHandle);
关于javascript - 在 map 标记上删除后添加监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34798598/