0

我在一页上有两张地图。地图加载正常,但地图上的两个标记仅触发最后一个信息窗口出现。我继续写 bla bla 因为如果我不这样做我就无法提交问题:-)

这是代码:

var places = {
    place1 : {
        long : 0.0,
        lat  : 0.0,
        address : 'Address...'
    },
    place2 : {
        long : 0.0,
        lat  : 0.0,
        address : 'Address...'
    }
};

for( var i in places ) {

    mapPositions[i] = new google.maps.LatLng( places[i].long, places[i].lat ),

    myOptions[i] = {
        zoom: 15,
        center: mapPositions[i],
        disableDefaultUI: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    $maps[i] = new google.maps.Map( document.getElementById( i + "_map_canvas" ), myOptions[i] );

    var title = 'Company ' + i;

    LatLngs[i] = new google.maps.LatLng( places[i].long, places[i].lat );

    markers[i] = new google.maps.Marker({
        position: $maps[i].getCenter(),
        map: $maps[i],
        title: title,
        location: places[i]
    });

    infowindows[i] = new google.maps.InfoWindow({
        content: '<div class="infoWindow">' + 
                    markers[i].title + ' - ' + markers[i].location.address + '<br/>' +
                '</div>'
    });

    google.maps.event.addListener( markers[i], 'click', function() {
        infowindows[i].open( $maps[i], markers[i] );
    });
}

谁能看到出了什么问题?

4

1 回答 1

0

Pretty much a closure issue it seems.

How do JavaScript closures work?

In this part:

google.maps.event.addListener( markers[i], 'click', function() {
    infowindows[i].open( $maps[i], markers[i] );
});

It will remember the last value of i. Just change it to

var iLocal = i;
google.maps.event.addListener( markers[i], 'click', function() {
    infowindows[iLocal].open( $maps[iLocal], markers[iLocal] );
});

This should help solve your closure problem.

于 2013-01-14T13:34:06.537 回答