0

In the below code, inside for loop variable 'i' seems to have the value 5 for all iterations. What have i done wrong? Code: http://pastebin.com/aHZ6HFKK

  var message = ['one', 'five', 'seven', 'nine', 'eight'];
  var loc = ["Moscow", "Delhi", "New York", "Tokyo", "Barcelona"];
  var geocoder = new google.maps.Geocoder();
  var i = 0;
  function initialize()
  {
    var p;
    var mapOptions = {zoom: 4, center: new google.maps.LatLng(22,75)};

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    for (i = 0; i < 5; i++)
    {
      geocoder.geocode({'address': loc[i]}, function(results, status){
        if(status == google.maps.GeocoderStatus.OK)
        {
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
          });
        }
        attachSecretMessage(marker, i);
      });
    }
  }

  function attachSecretMessage(marker, num)
  {
    var infowindow = new google.maps.InfoWindow({
      content: message[num]
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(marker.get('map'), marker);
    });
  }

  google.maps.event.addDomListener(window, 'load', initialize);
user2864740
  • 60,010
  • 15
  • 145
  • 220

1 Answers1

0

This happens because your use variable i in the callback. So firstly the for loop is executing lunching the requests resulting in var i becoming 5 then the callback functions are executed.

A possible solution would be:

var p;
var readyRequests = 0;
var mapOptions = {zoom: 4, center: new google.maps.LatLng(22,75)};

var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

for (i = 0; i < 5; i++)
{
  geocoder.geocode({'address': loc[i]}, function(results, status){
    if(status == google.maps.GeocoderStatus.OK)
    {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
    }
    attachSecretMessage(marker, readyRequests);
    readyRequests++;
  });
}
radu.cigmaian
  • 46
  • 1
  • 4