2016-01-14 199 views
2

当创建像这样我的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! 
}); 

这将创建标记好了,但是在行动上,我可以点击标记>鼠标移出和信息窗口保持目前>关闭infowindow。所有需要的行为。

但是再次悬停在标记信息窗口显示(如预期),但在碰到mouseout事件,我得到 -

JavaScript runtime error: Unable to get property 'apply' of undefined or null reference 

该错误是居住在谷歌API的JS文件,所以它是非常很难确定问题的根源在哪里。如何正确地恢复mouseout事件infowindow关闭?

回答

1

目前,您必须在事件分配一个匿名函数:

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. 
}); 

后来,您只需重新添加事件,因为您第一次做 - 因为你有一个不适用med函数,你不会失去声明!


如果你还在击中拆除原事件的错误,你might try being more specific

var listenerHandle = google.maps.event.addListener(marker, 'mouseout', mouseoutHandler); 
// later... 
google.maps.event.removeListener(listenerHandle); 
+0

亚瑟,好答案,我完全理解我们的逻辑,然而遗憾的是(甚至更具体减速)我仍然得到相同的未定义错误鼠标,任何其他想法? – Ebikeneser