使用谷歌地图3.44.10,我在谷歌地图上显示标记,我想隐藏标记当用户点击标记或按下退出时
定义glovar var
markerInfoWindow : null,
// hide marker when user clicked out of marker - it works ok
this.locationMap.addListener('click', function (event) {
if (self.markerInfoWindow) {
self.markerInfoWindow.close()
self.markerInfoWindow = null
}
});
google.maps.event.addListener(self.locationMarker, 'click', (function (marker, i) {
return function () {
self.markerInfoWindow = new google.maps.InfoWindow();
let content = ‘CONTENT TEXT’
self.markerInfoWindow.setContent(content); // I set content for marker and show it
self.markerInfoWindow.open(self.locationMap, self.locationMarker);
// Try to catch key events but - failed events are not triggered!
google.maps.event.addDomListener(self.markerInfoWindow, 'keyup keypress', function (e) {
console.log('keyup keypress e::')
console.log(e)
var code = (e.keyCode ? e.keyCode : e.which);
if (code === 27) {
if (self.markerInfoWindow) {
self.markerInfoWindow.close()
self.markerInfoWindow = null
}
}
});
}
})(this.locationMarker));
如何正确?
谢谢!
InfoWindow可以通过在InfoWindow上调用close()
方法来关闭,如文档中所述。
要在escape时关闭InfoWindow,只需侦听keyup
事件,检查键是否为";Escape";,如果是,请关闭"信息窗口"。同样,要在单击时关闭InfoWindow,请侦听click
事件。
示例(如果代码段加载不正确,也链接到jsfiddle(:
function initialize() {
let myLatLng = new google.maps.LatLng(40.71, -74.00),
myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
const infoWindow = new google.maps.InfoWindow({
content: "Blah Blah Blah",
});
marker.setMap(map);
// dismiss infoWindow on map click
marker.addListener("click", () => {
infoWindow.open(map, marker);
})
// dismiss infoWindow on escape press
document.body.addEventListener("keyup", (e) => {
if (e.key == "Escape") {
infoWindow.close();
}
});
map.addListener("click", () => {
infoWindow.close();
})
}
initialize();
#map-canvas {
height: 300px;
width: 600px;
background-color: #CCC;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>