问题
Can anyone help me code inside my eventListener so that an infowindow will do the following: open if it's currently closed, and close if it's currently open.
I've tried the following to no success...
google.maps.event.addListener(marker, 'click', function() {
if(infowindow.closed == true){
infowindow.open(map, marker)
}
else{
infowindow.close(map, marker)
}
})
回答1:
You can use something like this:
infoWindowClosed = true;
google.maps.event.addListener(marker, 'click', function() {
if (infoWindowClosed) {
infowindow.open(map, marker);
infoWindowClosed = false;
} else {
infowindow.close(map, marker)
infoWindowClosed = true;
}
})
回答2:
var currentInfoWindow = null;
then on every marker click event I do something like this:
var infowindow = new google.maps.InfoWindow({
content: "your content here"
});
google.maps.event.addListener(marker, 'click', function() {
if (currentInfoWindow != null) {
currentInfoWindow.close();
}
infowindow.open(map, marker);
currentInfoWindow = infowindow;
});
Source : https://groups.google.com/forum/#!topic/google-maps-js-api-v3/cA2VRg4TO1k
回答3:
Try first close infow window, and then get click to open again:
<script>
var onMarkerClick = function() {
var marker = this;
var latLng = marker.getPosition();
infoWindow.setContent('<h3>Marker position is:</h3>' +
latLng.lat() + ', ' + latLng.lng());
infoWindow.open(map, marker);
};
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
var marker1 = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(37.789879, -122.390442)
});
google.maps.event.addListener(marker1, 'click', onMarkerClick);
</script>
For more information visit the source code from this url:
- http://gmaps-samples-v3.googlecode.com/svn/trunk/single-infowindow/single-infowindow.html
来源:https://stackoverflow.com/questions/21772959/open-and-close-infowindow-onclick