Google Maps infowindow close event not working

浪尽此生 提交于 2021-01-28 18:14:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!