简体   繁体   中英

google maps api v3: infowindows distorted

When I plug in values for x instead of using a for loop, this code works. But when I use the for loop, the infowindow shows up distorted on the left side of the screen.

What the heel!

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]); }); 

}

You must use the closure in this case. Like this:

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

An economical way to approach this is to make the marker aware of its own index at the cost of just one Number property per marker, and avoiding the need to form a set of closures containing copies of 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);
    });
}

Providing the marker array and the content array remain static, or are compatibly managed, then this.x will reliably pull out the correct content for each marker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM