[英]How to add event listener to Map marker[ ] array
我有一个Google Map实现,它使用几个函数调用和marker []数组在地图上放置图钉。
它很好用,但是我无法弄清楚如何在函数中添加onClick事件或其他类型的事件侦听器,因为它没有明确定义标记变量。
我在哪里可以添加这样的内容?:
google.maps.event.addListener(markers, 'click', function() {
window.location.href = this.url;};
这是我的基本地图代码和功能:
var pinlocations = [
['1', {lat: 30.266758, lng: -97.739080}, 12, '/establishments/1111'],
['2', {lat: 30.267178, lng: -97.739050}, 11, '/establishments/1222'],
['3', {lat: 30.267458, lng: -97.741231}, 10, '/establishments/1333'],
['4', {lat: 30.388880, lng: -97.892276}, 9, '/establishments/1444']
];
var markers = [];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 30.267178, lng: -97.739050}
});
}
function drop() {
clearMarkers();
for (var i = 0; i < pinlocations.length; i++) {
var place = pinlocations[i];
addMarkerWithTimeout(place[1], place[0], place[2], place[3], i * 200);
}
}
function addMarkerWithTimeout(position, title, zindex, url, timeout) {
window.setTimeout(function() {
markers.push(new google.maps.Marker({
position: position,
map: map,
title: title,
zIndex: zindex,
url: url,
animation: google.maps.Animation.DROP
}));
}, timeout);
}
您无需将事件添加到数组中,而必须将其添加到数组中的每个元素中。 您可以使用.forEach()
数组方法执行此操作:
// Iterate the markers array
markers.forEach(function(marker){
// Set up a click event listener for each marker in the array
marker.addListener('click', function() {
window.location.href = marker.url;
});
});
或者,您可以采用另一种方法,并在创建每个标记时添加事件。
function addMarkerWithTimeout(position, title, zindex, url, timeout) {
window.setTimeout(function() {
markers.push(new google.maps.Marker({
position: position,
map: map,
title: title,
zIndex: zindex,
url: url,
animation: google.maps.Animation.DROP
}).addListener('click', function() {
window.location.href = this.url;
});
}, timeout);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.