我正在通过for循环从xml向Google Map添加一些标记。当我单击infowindow的标记弹出时,我得到一个错误,指出“无法调用方法”打开“未定义”。我在这里做错了什么?
的jQuery
var markers = xml.documentElement.getElementsByTagName('marker');
//function to create unique id
var getMarkerUniqueId = function(lat, lng) {
return lat + '_' + lng;
}
//function to get lat/lng
var getLatLng = function(lat,lng) {
return new google.maps.LatLng(lat, lng);
}
//cycle through and create map markers for each xml marker
for (var i = 0; i < markers.length; i++) {
//create vars to hold lat/lng from database
var lat = parseFloat(markers[i].getAttribute('lat'));
var lng = parseFloat(markers[i].getAttribute('lng'));
//create a unique id for the marker
var markerId = getMarkerUniqueId(lat, lng);
var name = markers[i].getAttribute('Type');
var html = '<b>' + name + '</b>';
//create the marker on the map
var marker = new google.maps.Marker({
map: the_Map,
position: getLatLng(lat, lng),
id: 'marker_' + markerId
});
//put the markerId into the cache
markers_arr[markerId] = marker;
infoWindow[i] = new google.maps.InfoWindow({
content: html,
position: getLatLng(lat, lng),
});
infobox[i] = google.maps.event.addListener(marker,'click',function() {
infoWindow[i].open(the_Map,marker);
});
}
答案 0 :(得分:2)
你需要一个闭包:
infobox[i] = google.maps.event.addListener(marker,'click',function() {
return function (windowToOpen) {
windowToOpen.open(the_Map,marker);
}(infoWindow[i]);
});
答案 1 :(得分:1)
当你执行infoWindow [i]时,i的开启值等于markers.length。你应该为每个infowindow创建一个上下文
修改代码:
function createContext (marker, iw){
google.maps.event.addListener(marker,'click',function() {
iw.open(the_Map,marker);
/ });
}
for (var i = 0; i < markers.length; i++) {
....
infobox[i] = createContext(marker, infoWindow[i]);
}