javascript - 变量覆盖到 for 循环中

标签 javascript json google-maps

我正在尝试使用 V3 向 Google map 添加标记。我将我的位置放入一个 json 对象(位置)中:

var num_places = places.length;
for(var i = 0; i < num_places; i++)
{
    place_lat_lng = new google.maps.LatLng(places[i].lat, places[i].lng);
    var infowindow = new google.maps.InfoWindow({
        content: '<h2>' + places[i].name + '</h2><p>' + places[i].body + '</p>'
    });
    var marker = new google.maps.Marker({
        position: place_lat_lng,
        map: mymap,
        title: places[i].name,
        zIndex: i
    });
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(mymap, marker);
    });
}

代码插入标记,但是当我点击其中任何一个时,信息窗口总是显示(并移动 map )到列表中的最后一个标记。

我尝试为信息窗口使用一个数组:

var infoWindow = new Array();
for(var i = 0; i < num_places; i++)
{
    [...]
    var infowindow[i] = new google.maps.InfoWindow({
        content: '<h2>' + places[i].name + '</h2><p>' + places[i].body + '</p>'
    });
    [...]
    google.maps.event.addListener(marker, 'click', function() {
        infowindow[i].open(mymap, marker);
    });
}

但什么都没有改变。

我哪里弄错了?

最佳答案

在 JavaScript 中,只有函数会创建新的作用域/闭包。因此,您只有一个 infowindow 变量,它被捕获到内部函数中,但最终将指向最后一个窗口。使用自调用函数设置新的关闭:

for (var i = 0; ...) {
    (function() {
        var infowindow = ...;
    })();
}

请注意,i 的值仍然不会被单独捕获。目前你似乎不需要它,但如果你需要,将它传递给函数以在函数内部创建它的本地版本:

(function(i) { // this is the new local i with the value passed in from the outside
    // ...accessible here
})(i); // this is the outer i

关于javascript - 变量覆盖到 for 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5070658/

相关文章:

javascript - 无法推送拦截器

javascript - Vue : Accessing Nested Object Component's Values

javascript - Select2 templateResult 数据没有可引用的元素

ios - 编码的 nsdata utf8 json,在 ios 中带有重音字符

python - 将 JSONL 文件加载为 JSON 对象

google-maps - 谷歌地图 : InvalidValueError: setLabel: not a string; and no text property

javascript - 在 Play Framework 2 中使用 javascript 路由

html - 创建或保存数据后重定向到索引而不是显示

javascript - 使用用户鼠标缩放时更改 map 类型

jquery - 关于css overflow和平移缩放的一些问题