我正在尝试为标记上的点击事件创建Google地图监听器。问题是事件没有解雇。我的下面的代码显示了如何初始化地图并将标记添加到地图中。我相信必须在初始化中添加事件监听器。
//initializing my variables
var marker = []; //final markers that wil go on the map
//this function loads the map on to the page.
function initialize() {
var mapOptions = {
center: {
lat: 0,
lng: 0
},
zoom: 2
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//listener for clicks on markers
google.maps.event.addListener(marker, 'click', markerClick);
//listener that listens for the map to load before calling the drop function
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
//this part runs when the mapobject is created and rendered
google.maps.event.addListenerOnce(map, 'idle', function() {
//this part runs when the mapobject shown for the first time
drop();
});
});
}
//drop function
function drop() {
for (var i = 0; i < pictureLocations.length; i++) {
setTimeout(function() {
addMarker();
}, i * 200);
}
}
//add marker function
function addMarker() {
marker.push(new google.maps.Marker({
position: pictureLocations[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
id: iterator
}));
iterator++;
}
当我点击标记时没有任何反应。我在点击功能中发出警报以引发javascript警报。
答案 0 :(得分:2)
问题是
marker
数组,这是一组标记。试试这个:
//initializing my variables
var marker = []; //final markers that wil go on the map
//this function loads the map on to the page.
function initialize() {
var mapOptions = {
center: {
lat: 0,
lng: 0
},
zoom: 2
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//listener that listens for the map to load before calling the drop function
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
//this part runs when the mapobject is created and rendered
google.maps.event.addListenerOnce(map, 'idle', function() {
//this part runs when the mapobject shown for the first time
drop();
});
});
}
//drop function
function drop() {
for (var i = 0; i < pictureLocations.length; i++) {
setTimeout(function() {
addMarker();
}, i * 200);
}
}
// define markerClick wich was not defined in your code
function markerClick(){
alert('click in the marker'):
}
//add marker function
function addMarker() {
var _marker = new google.maps.Marker({
position: pictureLocations[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
id: iterator
});
//listener for clicks on markers
google.maps.event.addListener(_marker, 'click', markerClick);
marker.push(_marker);
iterator++;
}
除此之外,您可以考虑详细了解适用于google.maps.Map
对象的google.maps.event
,您会发现idle
事件不是您认为的那样。< / p>