【发布时间】:2011-10-18 12:15:30
【问题描述】:
我正在尝试为在方向服务(Google Maps API V3)的回调函数中创建的标记设置 infoWindows。我尝试了许多不同的方法来做到这一点,但没有任何运气..
这是我的代码的骨架:
for(i=0;i<markersList.length;i++){
map = someMap
var request = myRequestObject;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
directionsService.route(request, (function (address) {
return function(response, status) {
//Use the directions service to do some stuff
//..Then create markers
var marker = new google.maps.Marker({
map: map,
title: address['title']
});
//push the marker to a list of markers attached to the map
//this can be useful to delete all markers in a later step
map.markers.push(marker);
//Creating multiple instances of infoWindows works fine though..
//However, Creating 1 info window for the whole map doesn't work from here
//If I try that, I'd set the same content for all info windows
//which is not what I want.
}
}
)(markersList[i])
);
}
我试过这样做,但也没有用:
//add setInfo as a custom function to my map
//then call it to iterate over all markers and add info windows
google.maps.Map.prototype.setInfo = function() {
for(var i=0; i < this.markers.length; i++){
infowindow.setContent(this.markers[i].getTitle());
google.maps.event.addListener(this.markers[i], 'click', function(){
infowindow.close();
infowindow.open(map,this.markers[i]);
});
}
};
然后,在我的主 for 循环之外,我将在执行完方向服务.route(检查第一个代码块)后调用此函数。但是,由于某种原因,它永远不会找到任何附加到地图上的标记..
关于如何将正确的 infoWindows 分配给地图标记有任何想法吗? 我想要 1 个 infoWindow 实例,以便在单击新的 infoWindow 时关闭它 (infoWindow.close())。
谢谢!
【问题讨论】:
标签: javascript callback google-maps-api-3 closures