3

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.

Kemal Fadillah
  • 9,760
  • 3
  • 45
  • 63

3 Answers3

1

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

The problem is that ville is not an array, so by the time the for loop finishes, ville only has the value of the last item in your initial array (png3). You need call the function right after setting the value to ville

What have you tried
  • 11,018
  • 4
  • 31
  • 45
0

The geocode call is asynchronous, which means that you will loop through all the places and send requests, then the responses will arrive. At that time you have already run through the loop, and the ville variable has the value of the last place.

Put a function expression around the code in the loop, so that each iteration has its own copy of the variable:

for (var i = 0; i < Villes.length; i++) {

  (function(ville){

    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);
      }
    });

  })(Villes[i]);

}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005