2016-01-14 151 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