[英]Google Maps listener closure
I am trying to add an info window to a marker by looping through an array of objects and creating the markers and then checking if the object has a content property, and if it does, then adding an event listener on the marker to open an info window. 我正在尝试通过遍历对象数组并创建标记来向标记添加信息窗口,然后检查对象是否具有content属性,如果存在,则在标记上添加事件侦听器以打开信息窗口。
I'm almost there but have run into a closure related problem in the loop. 我快到了,但是在循环中遇到了与闭包相关的问题。 I always end up with the last object in the array's content property.
我总是以数组的content属性中的最后一个对象结束。 I thought I could get around this by wrapping the event listener callback in a function and passing in the object
我以为可以通过将事件侦听器回调包装在函数中并传入对象来解决此问题
Can anyone tell me what I am doing wrong with my closure when assigning the event listener: 谁能告诉我在分配事件侦听器时我在关闭时出错了:
_addMarkers = function () {
var marker, latlon, title, infowindow, content;
_options.markers.map(function (marker) {
title = marker.title;
content = marker && marker.window_content;
latlon = _getLatLon(marker.lat, marker.lon);
if (latlon) {
marker = new google.maps.Marker({
position : latlon,
title : title,
map : _map
});
}
if (content) {
infowindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', (function (_marker) {
infowindow.open(_map, _marker);
}(marker)));
}
});
}
Fixed it. 修复。 Changed the bit adding the listener to:
将添加侦听器的位更改为:
if (content) {
google.maps.event.addListener(marker, 'click', (function (content, _marker) {
return function () {
infowindow = new google.maps.InfoWindow({
content: content
});
infowindow.open(_map, _marker);
};
}(content, marker)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.