我正在尝试使用以下代码生成多个InfoWindows:编辑:为了澄清,我希望所有窗口同时打开。
for (var i = 0; i < 3; i++) {
var markerOptions = {position:point[i], map:map};
var marker = new google.maps.Marker(markerOptions);
content = "Hello " + i;
infowindow[i] = new google.maps.InfoWindow({content: content});
google.maps.event.addListener(marker, 'mouseover', function()
{
infowindow[i].open(map,this);
});
}
但是,我在Chrome中遇到以下错误:未捕获的TypeError:无法调用未定义的方法'open'。
当我使用普通变量“infowindow”而不是数组时,单个infowindow会按预期显示。
答案 0 :(得分:1)
您只能创建一个infoWindow。我用过这样的项目:
var infowindow = new google.maps.InfoWindow();
for (var i = 0; i < 3; i++)
{
var markerOptions = {position:point[i], map:map, html:'Hello' };
var marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'mouseover', function()
{
infowindow.setContent(this.html); // this is the trick: html attribute on markerOptions :), I used a array here
infowindow.open(map,this);
});
}
答案 1 :(得分:0)
你有输出infowindow [i]到控制台(firebug)看看它是否是你所期待的?我认为通常这样做的方法是生成一个infowindow对象并重用/移动和更改infowindow的内容。
此链接可能很方便:http://www.svennerberg.com/2009/09/google-maps-api-3-infowindows/
答案 2 :(得分:0)
工作样本
var map;
var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP };
var infowindow = new google.maps.InfoWindow();
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
point = [];
point[0] = new google.maps.LatLng(0.0,0.0);
point[1] = new google.maps.LatLng(0.0,10.0);
point[2] = new google.maps.LatLng(0.0,20.0);
for (var i = 0; i < 3; i++) {
var content = "Hello"+i;
addInfowindows(point[i], content )
}
}
function addInfowindows(point, content){
var markerOptions = {position:point, map:map};
var marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'mouseover', function()
{
infowindow.setContent(content);
infowindow.open(map,this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
答案 3 :(得分:0)
为了实现我的目标,我学会了a closure is needed:
for (var i = 0; i < 3; i++)
{
(function(i) {
var markerOptions = {position:point[i], map:map, html:'Hello' };
var marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'mouseover', function()
{
infowindow.setContent(this.html); // this is the trick: html attribute on markerOptions :), I used a array here
infowindow.open(map,this);
});
})(i);
}