views:

179

answers:

1

Hi guys, 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.png";
    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!

+3  A: 

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

Jeffery To
Partly works, now all the markers have infowindows, but...I have used this function GEvent.addListener( marker[i] , 'click', function() { this.openInfoWindow( 'tower'+i ) ; });and it would tag all markers as 'tower6', rather then its current number in the array.
WORKS! Thanks man!