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



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

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

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

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;
}               
});

概念验证小提琴

代码片段:

// 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>

最新更新