问题
I have create an infowindow in google maps as:
var setInfoWindow = function() {
infoWindowOpen = true;
return new google.maps.InfoWindow({
content: businessAddress
});
}
This is the open event for infowindow. It is working
google.maps.event.addListener(marker, 'click', function() {
if(!infoWindowOpen) {
setInfoWindow().open(map,marker);
currentMark = this;
}
});
This is the close event for infowindow. It is not working
google.maps.event.addListener(infowindow,'closeclick',function(){
var infowindow = setInfoWindow();
console.log("ddd");
currentMark.setMap(null);
});
Here my open event is working but the close event is not getting triggered. How can I solve this issue.
回答1:
You need to add the 'closeclick' listener to the google.maps.InfoWindow
object once it exists.
var infowindow;
google.maps.event.addListener(marker, 'click', function() {
if (!infoWindowOpen) {
infowindow = setInfoWindow();
infowindow.open(map, this);
google.maps.event.addListener(infowindow, 'closeclick', function() {
console.log("ddd");
currentMark.setMap(null);
infoWindowOpen = false;
});
currentMark = this;
}
});
proof of concept fiddle
code snippet:
var infowindow;
var infoWindowOpen;
var businessAddress = "Palo Alto, CA"
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
})
google.maps.event.addListener(marker, 'click', function() {
if (!infoWindowOpen) {
infowindow = setInfoWindow();
infowindow.open(map, this);
google.maps.event.addListener(infowindow, 'closeclick', function() {
console.log("ddd");
currentMark.setMap(null);
infoWindowOpen = false;
});
currentMark = this;
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
var setInfoWindow = function() {
infoWindowOpen = true;
return new google.maps.InfoWindow({
content: businessAddress
});
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
来源:https://stackoverflow.com/questions/48153336/google-maps-infowindow-close-event-not-working