2010-12-12 3 views
0

Ich bin mir sicher, das ist wirklich einfach, aber ich hatte nicht viel Glück herauszufinden, was los ist. Ich erstelle ein leeres Array (Standorte), fülle es mit Standortobjekten in der getPartnerLocations-Funktion und versuche dann, die Standorte auf der Karte mit der drop-Funktion zu plotten. Das Problem, das ich habe, ist, dass innerhalb der drop Funktion das Standort-Array, das Zeug darin hat, eine Länge von Null zurückgibt, so dass die Schleife in der nicht funktioniert. Irgendwelche Tipps oder Ideen über das, was hier vor sich geht, würden sehr geschätzt werden.Javascript Array zeigt 0 Länge bei der Belegung

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

ist es möglich, eine abgespeckte Demo auf http://jsfiddle.net/ zu veröffentlichen? –

Antwort

2

geocode ist eine asynchrone Funktion.

Der Rückruf wird erst nach einer gewissen Zeit ausgeführt nach Sie rufen drop.
Daher, wenn Sie drop aufrufen, ist das Array immer noch leer.

Sie müssen initialize und drop aufrufen, nachdem der letzte AJAX-Anruf im Callback geocode antwortet.

Verwandte Themen