google maps api v3:infowindows扭曲了

时间:2013-09-27 05:58:52

标签: javascript google-maps google-maps-api-3

当我插入x的值而不是使用for循环时,此代码可以正常工作。但是当我使用for循环时,infowindow会在屏幕左侧显示失真。

脚后跟!

  

for(var x = 0; x< data.page_size; x ++){

var position = new google.maps.LatLng(
  data.events.event[x]['latitude'],
  data.events.event[x]['longitude']);

marker.push(
  new google.maps.Marker({
    position: position, 
    map: map, 
    icon: image}
));

 google.maps.event.addListener(marker[x], 'click', function() {
  infowindow.setContent(content[x]);
  infowindow.open(map, marker[x]);
});
     

}

2 个答案:

答案 0 :(得分:1)

在这种情况下,您必须使用闭包。像这样:

(function(m,c){
    google.maps.event.addListener(m, 'click', function() {
        infowindow.setContent(c);
        infowindow.open(map, m);
    });
})(marker[x],content[x])

答案 1 :(得分:0)

解决这个问题的一种经济方法是让标记识别出自己的索引,代价是每个标记只有一个Number属性,并且无需形成一组包含content[x]副本的闭包。 / p>

for (var x = 0; x < data.page_size; x++) {
    ...
    marker[x].x = x;//make the marker aware of its own index
    google.maps.event.addListener(marker[x], 'click', function() {
        infowindow.setContent(content[this.x]);
        infowindow.open(map, this);
    });
}

提供marker数组和content数组保持静态或兼容管理,然后this.x将可靠地为每个标记提取正确的内容。