2010-12-12 90 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