【发布时间】:2015-02-06 07:11:36
【问题描述】:
我正在尝试为标记上的点击事件创建 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++;
}
当我点击标记时,没有任何反应。我在 click 函数中有一个警报,会导致 javascript 警报。
【问题讨论】:
-
看事物的顺序。添加 Listner 时,标记尚不存在。此外,marker 是一组标记的糟糕名称。这非常令人困惑。
-
看看the examples in the documentation可能不会有什么坏处
-
@EmmanuelDelay 感谢您的评论!我在 drop 函数调用之后以及 addMarker 函数中都放置了监听器,但无济于事。听者似乎没有上钩。
-
请提供一个Minimal, Complete, Tested and Readable example 来证明您的问题或查看answer to the linked question。
markerClick是什么?您编写的代码将不起作用,因为在创建点击侦听器时未定义标记(如 Emmanuel Delay 所示)。
标签: javascript google-maps google-maps-api-3