views:

21

answers:

1

Hello, I'm trying to add an event listener to each icon on the map when it's pressed. I'm storing the information in the database and the value that I'm wanting to retrive is "i" however when I output "i", I get it's last value which is 5 (there are 6 objects being drawn onto the map)

Below is the code, what would be the best way to get the value of i, and not the object itself.

var drawLotLoc = function(id) {

    var lotLoc = new GIcon(G_DEFAULT_ICON);             // create icon object
    lotLoc.image = url+"images/markers/lotLocation.gif";     // set the icon image
    lotLoc.shadow = "";                                 // no shadow
    lotLoc.iconSize = new GSize(24, 24);                // set the size
    var markerOptions = { icon: lotLoc };               

    $.post(opts.postScript, {action: 'drawlotLoc', id: id}, function(data) {

        var markers = new Array();
        // lotLoc[x].description
        // lotLoc[x].lat
        // lotLoc[x].lng
        // lotLoc[x].nighbourhood
        // lotLoc[x].lot
        var lotLoc = $.evalJSON(data);

        for(var i=0; i<lotLoc.length; i++) {
            var spLat = parseFloat(lotLoc[i].lat);
            var spLng = parseFloat(lotLoc[i].lng);

            var latlng = new GLatLng(spLat, spLng)
            markers[i] = new GMarker(latlng, markerOptions);

            myMap.addOverlay(markers[i]);

            GEvent.addListener(markers[i], "click", function() {
                console.log(i);     // returning 5 in all cases. 
                                    // I _need_ this to be unique to the object being clicked.
                console.log(this);
            });
        }
    });
+1  A: 

You have an issue with closures. Your functions see i's last valuse. Simply add another closure to fix your error:

for(var i=0; i<lotLoc.length; i++) {
    (function(i){
        // ...
    })(i); //run the function with i as argument
}//for
Kobi
That did it, thanks a lot
cdnicoll