for循环内部的变量对于所有迭代具有相同的值

时间:2014-03-23 19:46:13

标签: javascript google-maps for-loop

在下面的代码中,for循环变量' i'似乎所有迭代的值都是5。我做错了什么? 码: 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);

1 个答案:

答案 0 :(得分:0)

这是因为您在回调中使用变量i。首先,for循环正在执行求助,导致var i变为5,然后执行回调函数。

可能的解决方案是:

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