开发者

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(func开发者_如何学Pythontion(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜