如何通过再次单击标记关闭打开的 google 地图信息窗口

How to close an open google maps infowindow by clicking marker again

我正在尝试通过再次单击标记来关闭打开的 google 地图信息窗口。目前只有单击地图或其他标记时如何关闭所有其他信息窗口的问题。

如何通过再次单击同一标记来关闭打开的 google 地图信息窗口?目前我只能通过点击信息窗口右上角的叉号来关闭信息窗口。

这是我试过的,但它甚至没有打开信息窗口:

    EncoreMarker.addListener('click', function () {
        if (EncoreInfoCard.open) {
            EncoreInfoCard.close(map, EncoreMarker);
        }
        else {
            EncoreInfoCard.open(map, EncoreMarker);
        }               
    });

您的代码将无法运行,因为 open 是一个打开 InfoWindow 的函数,而不是一个 boolean 来判断它是否打开。

这对我有用:

EncoreMarker.addListener('click', function () {
    // create a custom property of the InfoWindow, defaults to a value that evaluates as false
    if (EncoreInfoCard.isOpen) { 
        EncoreInfoCard.close(map, EncoreMarker);
        EncoreInfoCard.isOpen = false;
    }
    else {
        EncoreInfoCard.open(map, EncoreMarker);
        EncoreInfoCard.isOpen = true;
    }               
});

proof of concept fiddle

代码片段:

// This example displays a marker at the center of Australia.
// When the user clicks the marker, an info window opens.
// When the user clicks the makrer again, the info window closes.

function initMap() {
  var uluru = {
    lat: -25.363,
    lng: 131.044
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: uluru
  });

  var EncoreInfoCard = new google.maps.InfoWindow({
    content: "<b>This is a Test</b>"
  });
  google.maps.event.addListener(EncoreInfoCard, 'closeclick', function() {
    EncoreInfoCard.isOpen = false;
  });
  var EncoreMarker = new google.maps.Marker({
    position: uluru,
    map: map,
    title: 'Uluru (Ayers Rock)'
  });

  EncoreMarker.addListener('click', function() {
    if (EncoreInfoCard.isOpen) {
      EncoreInfoCard.close(map, EncoreMarker);
      EncoreInfoCard.isOpen = false;
    } else {
      EncoreInfoCard.open(map, EncoreMarker);
      EncoreInfoCard.isOpen = true;
    }
  });
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>