Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array with a for in JavaScript not change every var

Hi I have some trouble with an array with a for in JavaScript. Let's have a look:

var Villes = [
  ['Versailles+France', 'upr2.png'],
  ['Paris+France', 'upr5.png'],
  ['Bruxelle+Belgique', 'upr4.png'],
  ['Manchester+Angleterre', 'upr1.png'],
  ['Monaco+Monaco', 'upr3.png']
];

function initialize() {
  var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(46.225453,2.219238),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
  var geocoder = new google.maps.Geocoder();
  for (var i = 0; i < Villes.length; i++) {
    var ville = Villes[i];
    geocoder.geocode( { 'address': ville[0]}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({position: results[0].geometry.location,map: map,icon: ville[1]});
        alert(ville[1] + status);
      } else {
        alert("Geocode n'a pas fonctionner. Erreur: " + status);
      }
    });
  }
}

My Map comes with all my marker but the icon never change like ville[1] is a static call to upr3.png I'm not used to JS and it's the first time I see that.

like image 980
Sylvain Gargasson Avatar asked Jul 30 '26 00:07

Sylvain Gargasson


1 Answers

By the time the callback you give to geocode is called, i has the value of end of loop.

The usual generic solution is to protect it by an immediately called function expression :

for (var i = 0; i < Villes.length; i++) {
     (function(ville){
        geocoder.geocode( { 'address': ville[0]}, function(results, status)
           ...
        });
     })(Villes[i]);
}

As the scope of a variable is the function in which it is declared, this makes the new variable ville immune to the variation of the loop.

like image 50
Denys Séguret Avatar answered Jul 31 '26 15:07

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!