简体   繁体   中英

Javascript array showing 0 length when populated

I'm sure this is really simple but I haven't had much luck figuring out what's wrong. I'm creating an empty array (locations), filling it with location objects in the getPartnerLocations function and then trying to plot the locations on the map with the drop function. The problem I'm having is that inside the drop function the locations array which has stuff in it is returning a length of zero so the loop in the isn't working. Any tips or ideas about what's going on here would be greatly appreciated.

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(); 

geocode is an asynchronous function.

The callback doesn't execute until some time after you call drop .
Therefore, when you call drop , the array is still empty.

You need to call initialize and drop after the last AJAX call replies, in the geocode callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM