与许多发现自己处于StackOverflow状态的人一样,我对Javascript和Google Maps API有些陌生。几年前,我对如何调用jamesaharvey发布的代码感到困惑。
我的项目版本使用infowindows,但必须手动关闭。这是一种更优雅的方式。我无法让它发挥作用。我使用以下
var infowindow = new google.maps.InfoWindow();
function getInfoWindowEvent(marker) {
infowindow.close()
infowindow.setContent("huh?");
infowindow.open(map, marker);
}
我有多个正确显示的标记。
var MAPA = new google.maps.Marker({position: {lat: 12.3400, lng: -12.3450}, map: map, title: 'A Marker'});
var MAPB = new google.maps.Marker({position: {lat: 12.3450, lng: -12.3455}, map: map, title: 'B Marker'});
var MAPC = new google.maps.Marker({position: {lat: 12.3460, lng: -12.3460}, map: map, title: 'C Marker'});
我的假设是,我需要调用为每个标记添加一个监听器,以便在单击标记时调用getInfoWindowEvent。像这样的东西。
MAPA.addListener('click', getInfoWindowEvent(MAPA));
MAPB.addListener('click', getInfoWindowEvent(MAPB));
MAPC.addListener('click', getInfoWindowEvent(MAPC));
我知道我在这里错过了一些东西。感谢
答案 0 :(得分:0)
.addListener
函数的第二个参数需要是函数指针,而不是(必然)函数。使用带有MouseEvent
参数的函数,如下所示:
MAPA.addListener('click', getInfoWindowEvent);
或者从函数返回一个函数(第二个参数中的函数将被执行,其返回值被用作click函数):
function getInfoWindowEvent(marker) {
return function(evt) {
infowindow.close()
infowindow.setContent("huh?<br>"+this.getPosition().toUrlValue(6));
infowindow.open(map, marker);
}
}
代码段
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(12.34, -12.34),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
map.addListener('click', function(evt) {
infowindow.close()
});
function getInfoWindowEvent(marker) {
return function(evt) {
infowindow.close()
infowindow.setContent("huh?<br>" + this.getPosition().toUrlValue(6));
infowindow.open(map, marker);
}
}
var MAPA = new google.maps.Marker({
position: {
lat: 12.3400,
lng: -12.3450
},
map: map,
title: 'A Marker'
});
var MAPB = new google.maps.Marker({
position: {
lat: 12.3450,
lng: -12.3455
},
map: map,
title: 'B Marker'
});
var MAPC = new google.maps.Marker({
position: {
lat: 12.3460,
lng: -12.3460
},
map: map,
title: 'C Marker'
});
MAPA.addListener('click', getInfoWindowEvent(MAPA));
MAPB.addListener('click', getInfoWindowEvent(MAPB));
MAPC.addListener('click', getInfoWindowEvent(MAPC));
}
google.maps.event.addDomListener(window, "load", initialize);
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>