在javascript中循环获得意外结果

时间:2014-11-16 22:38:57

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

我正在尝试将标记添加到谷歌地图中,​​这些标记上有一个数字,但是我得到的是整个循环中重复的相同标记为什么会这样?这是我的代码,

function codeAddress() {
var address = ['hd3 3nn', 'hd6 3qf'];
for (var i = 0; i < address.length; i++) {
    var num = i;
    geocoder.geocode( { 'address': address[i]}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var image = new google.maps.MarkerImage('/~udders/wp-content/themes/muslenh2/img/markers/marker' + num + '.png',
                  new google.maps.Size(20, 34),
                  new google.maps.Point(0, 0),
                  new google.maps.Point(10, 34));
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                icon: image,
                position: results[0].geometry.location
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

}

基本上这个/ ~udders / wp-content / themes / m / img / markers / marker&#39; + num +&#39; .png正在创建,/〜dudders / wp-content / themes / m / img / markers / marker1.png一个是最后一个循环中的数字,它似乎覆盖了所有以前的图标图片。

1 个答案:

答案 0 :(得分:1)

这是因为how Javascript closures work

您可以通过创建一个返回回调函数的单独函数来解决它。

function codeAddress() {
    var address = ['hd3 3nn', 'hd6 3qf'];
    for (var i = 0; i < address.length; i++) {
        geocoder.geocode({'address': address[i]}, getGeocoderCallBack(i));
    }
}

function getGeocoderCallback(num) {
    return function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var image = new google.maps.MarkerImage('/~udders/wp-content/themes/muslenh2/img/markers/marker' + num + '.png',
            new google.maps.Size(20, 34),
            new google.maps.Point(0, 0),
            new google.maps.Point(10, 34));
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                icon: image,
                position: results[0].geometry.location
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    };
}