2010-12-12 100 views
0

我确定这很简单,但我没有很好的计算出错的地方。我正在创建一个空阵列(位置),用getPartnerLocations函数中的位置对象填充它,然后尝试使用drop函数绘制地图上的位置。我遇到的问题是在drop函数中,位置数组中有东西的地方返回的长度为零,因此循环不起作用。任何关于这里发生的提示或想法将不胜感激。Javascript数组显示长度为0时的长度

var markers = []; 
var locations = []; 
var iterator = 0; 
var map; 
var geocoder; 
var newYork = new google.maps.LatLng(40.7143528, -74.0059731); 


    function initialize() { 
    var mapOptions = { 
     zoom: 12, 
     mapTypeId: google.maps.MapTypeId.ROADMAP, 
     center: newYork 
    }; 

    map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions); 

    } 

    function getPartnerLocations() { 
     geocoder = new google.maps.Geocoder();  
     $('.partner').each(function(index){ 

      var street = $('.partner-streetaddress',this).text(); 
      var city = $('.partner-city',this).text(); 
      var state = $('.partner-state',this).text(); 
      var country = $('.partner-country',this).text(); 

      var address = street + ', ' + city + ', ' + state + ', ' + country; 

      geocoder.geocode({ 'address': address}, function(results, status) 
      { 

       if (status == google.maps.GeocoderStatus.OK) 
       { 
        locations.push(results[0].geometry.location); 
        console.log(locations[index]); 
       } 
       else 
       { 
        console.log('failed to geocode address: ' + address); 
       } 
      }); 

     }); 
     initialize(); 
     drop(); 
    } 

    function addMarker() { 
    console.log('add marker function'); 
    markers.push(new google.maps.Marker({ 
     position: locations[iterator], 
     map: map, 
     draggable: false, 
     animation: google.maps.Animation.DROP 
    })); 
    iterator++; 
    } 

    function drop() 
    { 
    console.log(locations.length); 
    for (var i = 0; i < locations.length; i++) { 
     setTimeout(function() { 
     addMarker(); 
     }, i * 200); 
    } 
    } 

getPartnerLocations(); 
+0

是否可以在http://jsfiddle.net/上发布精简版演示? – 2010-12-12 19:56:09

回答

2

geocode是一个异步功能。

该回调不会执行,直到之后您拨打drop
因此,当您调用drop时,该数组仍为空。

您需要在geocode回调中最后一次AJAX呼叫回复后致电initializedrop