javascript - 在 map 标记上删除后添加监听器

标签 javascript google-maps google-maps-markers

创建我的 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/

相关文章:

javascript - 选择下拉方向

javascript - ng-click 动态创建的按钮的范围在 Google map 上不起作用

javascript - 谷歌 javascript map getCurrentPosition

android - 如何处理谷歌地图上具有相同位置的多个标记?

google-maps-api-3 - Google map 中的自定义标记图标在动画之前弹出

javascript - jQuery 根据复选框状态切换 div 中的文本

javascript - 从模板访问对象属性到函数 - Angular

javascript - 如何在 Google map 中创建定向(成 Angular )标记?

javascript - 确定放置在 div 中的文本量以最大化最后一行的宽度

android - 如何在 MapView 上绘制来自谷歌地图的预建 map