Google Maps, marker info window won't show up?
I have written this code that loops through an array of lat/long coordinates and places a marker at each of the coordinate. Everything forks fine, exempt the info window won't appear once the marker is clicked.
var ExpTowerIcon = new GIcon();
ExpTowerIcon.image = "tower.p开发者_高级运维ng";
ExpTowerIcon.iconSize = new GSize(75, 75);
ExpTowerIcon.iconAnchor = new GPoint(37, 65);
ExpTowerIcon.infoWindowAnchor = new GPoint(37, 20);
var marker=new Array();
for ( i=0 ; i < lat.length ; i++ ) {
var MarkerPoint = new GLatLng(lat[i],long[i]);
marker[i] = new GMarker(MarkerPoint,{icon:ExpTowerIcon})
map.addOverlay( marker[i] );
GEvent.addListener( marker[i] , 'click', function() { marker[i].openInfoWindowHtml('Hello!') ; });
var polyline = new GPolyline([ new GLatLng(lat[i],long[i]) , new GLatLng(lat[i+1],long[i+1]) ], "#ff0000", 5);
map.addOverlay(polyline);
}
Any ideas? Thanks!
The click handler:
function() { window['marker'+i].openInfoWindowHtml('Hello!') ; }
references the (global) variable i, which will be set to lat.length when the for loop exits.
I suggest:
function() { this.openInfoWindowHtml('Hello!') ; }
Edit:
If you need to have the marker number inside the click event handler, I suggest:
function getHandler(i) {
return function () { this.openInfoWindow('tower' + i) ; };
}
for (i = 0; i < lat.length; i++) {
...
GEvent.addListener( marker[i] , 'click', getHandler(i));
...
}
This binds the variable i to the click handler (the handler is now a closure). For more on closures, see Working with Closures - MDC
精彩评论