谷歌地图API v3:信息窗口失真

google maps api v3: infowindows distorted

本文关键字:信息窗 窗口 失真 信息 API v3 谷歌地图      更新时间:2023-09-26

当我插入 x 的值而不是使用 for 循环时,这段代码有效。 但是当我使用 for 循环时,信息窗口在屏幕左侧显示失真。

什么脚跟!

for (var x = 0; 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]);
});

}

在这种情况下,您必须使用闭包。喜欢这个:

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

此目的的一种经济方法是使标记知道自己的索引,但代价是每个标记只有一个 Number 属性,并且避免需要形成一组包含content[x]副本的闭包。

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将可靠地为每个标记提取正确的内容。