我正在尝试为标记上的点击事件创建一个 Google map 监听器。问题是该事件没有触发。下面的代码显示了如何初始化 map 并向 map 添加标记。我认为必须在初始化中添加事件监听器。
//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 警报。
最佳答案
问题是
- 您正在尝试将监听器添加到
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
事件并不是你想象的那样。
关于javascript - 谷歌地图标记点击事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27361233/