Pergunta

Meu código

// Faça um pedido de Ajax e obtenha resposta JSON

for (var i = 0; i < data.results.length; i++) {  
    result = data.results[i];
    // do stuff and create google maps marker    
    marker = new google.maps.Marker({  
        position: new google.maps.LatLng(result.lat, result.lng),   
        map: map,  
        id: result.id  
    });  
    google.maps.event.addListener(marker, 'click', function() {  
        createWindow(marker.id); //<==== this doesn't work because marker always points to the last results when this function is called
    });  

}

Como resolver isso?

Foi útil?

Solução

Experimente isso:

with ({ mark: marker }) {
    google.maps.event.addListener(mark, 'click', function() {  
        createWindow(mark.id);
    });
}

Um exemplo que demonstra o uso de with:

for (var i = 0; i < 10; i++) {
    setTimeout(function() { console.log(i); }, 1000);
}

O acima vai registrar 10 dez vezes.

for (var i = 0; i < 10; i++) {
    with ({ foo: i }) {
        setTimeout(function() { console.log(foo); }, 1000);
    }
}

Isso vai registrar 0 para 9, conforme desejado, obrigado a with Apresentando um novo escopo.

JavaScript 1.7 tem um let declaração que é melhor, mas até que isso seja amplamente suportado, você pode usar with.

E use var para suas variáveis.

Outras dicas

o Problema de fechamento clássico ataca novamente!

  google.maps.event.addListener(marker, 'click', function(id) {
    return function(){
      createWindow(id); //<==== this doesn't work because marker always points to the last results when this function is called
    }
  }(marker.id));     

tente este

var marker = new Array();
for (var i = 0; i < data.results.length; i++) {  
    result = data.results[i];
    // do stuff and create google maps marker    
    marker[i] = new google.maps.Marker({  
        position: new google.maps.LatLng(result.lat, result.lng),   
        map: map,  
        id: result.id  
    });  
    google.maps.event.addListener(marker[i], 'click', example(marker[i].id));  

}

Crie nova função

function example(my_window){
    return function(){
        createWindow(my_window);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top