我在一个页面上有2张地图。地图加载正常,但地图上的两个标记仅触发显示的最后一个信息窗口。我继续写bla bla因为我不能提交问题,如果我不知道: - )
这里是代码:
var places = {
place1 : {
long : 0.0,
lat : 0.0,
address : 'Address...'
},
place2 : {
long : 0.0,
lat : 0.0,
address : 'Address...'
}
};
for( var i in places ) {
mapPositions[i] = new google.maps.LatLng( places[i].long, places[i].lat ),
myOptions[i] = {
zoom: 15,
center: mapPositions[i],
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
$maps[i] = new google.maps.Map( document.getElementById( i + "_map_canvas" ), myOptions[i] );
var title = 'Company ' + i;
LatLngs[i] = new google.maps.LatLng( places[i].long, places[i].lat );
markers[i] = new google.maps.Marker({
position: $maps[i].getCenter(),
map: $maps[i],
title: title,
location: places[i]
});
infowindows[i] = new google.maps.InfoWindow({
content: '<div class="infoWindow">' +
markers[i].title + ' - ' + markers[i].location.address + '<br/>' +
'</div>'
});
google.maps.event.addListener( markers[i], 'click', function() {
infowindows[i].open( $maps[i], markers[i] );
});
}
有谁能看到什么问题?
答案 0 :(得分:0)
似乎是一个封闭问题。
How do JavaScript closures work?
在这部分:
google.maps.event.addListener( markers[i], 'click', function() {
infowindows[i].open( $maps[i], markers[i] );
});
它会记住i的最后一个值。只需将其更改为
即可var iLocal = i;
google.maps.event.addListener( markers[i], 'click', function() {
infowindows[iLocal].open( $maps[iLocal], markers[iLocal] );
});
这应该有助于解决您的关闭问题。