Pergunta

Eu estou tentando adicionar um ouvinte de evento para cada ícone no mapa quando é pressionado. Estou armazenar as informações no banco de dados e o valor que eu estou querendo retrive é "i", no entanto, quando eu saída "i", eu recebo é o último valor que é 5 (há 6 objetos que estão sendo atraídos para o mapa)

Abaixo está o código, o que seria a melhor maneira de obter o valor de i, e não o objeto em si.

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);
            });
        }
    });
Foi útil?

Solução

Você tem um problema com encerramentos. Suas funções ver o último valor de i. Basta adicionar outro fechamento para corrigir o seu erro:

for(var i=0; i<lotLoc.length; i++) {
    (function(i){
        // ...
    })(i); //run the function with i as argument
}//for
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top