for 循环中 getJSON 后的回调

callback after getJSON in for loop

所以我在 for 循环中执行 getJSON 请求。 在 getJSON 函数回调中,我将值推送到全局数组中。

现在无法访问 for 循环外的全局数组,因为我读到 getJSON 是异步的...

我尝试制作标志和其他回调函数,但看起来甚至 for 循环结束得比 getJSON 请求更快(即使使用 getJSON 函数插入 for 循环)..

function initMap(){

// Address value variables
var country;
var city;
var addresses = [];
var locations = [];

// Google maps variables
var myOptions = {
    zoom: 5,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: 'terrain',
    scrollwheel: false,
    navigationControl: true,
    mapTypeControl: true,
    scaleControl: true,
    draggable: true
};
var marker;
var bounds = new google.maps.LatLngBounds();

// Get country city values
$('li.deal-itinerary-item').each(function(){
    country = $(this).data('country');
    city = $(this).data('city');
    if( country && city ){
        addresses.push(country + ' ' + city);
    }
});

var map = new google.maps.Map($('#map_canvas')[0], myOptions);

for (var x = 0; x < addresses.length; x++) {

    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {

        var p = data.results[0].geometry.location;
        var latlng = new google.maps.LatLng(p.lat, p.lng);

        locations.push({lat: p.lat, lng: p.lng});

        marker = new google.maps.Marker({
            position: latlng,
            map: map
        });

        bounds.extend(marker.position);

    });

}

// CONSOLE LOG NOT WORKING HERE
console.log(locations);

map.fitBounds(bounds);

zoomChangeBoundsListener = 
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
    if (this.getZoom()){
        this.setZoom(6);
    }
});
setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);

};
google.maps.event.addDomListener(window, 'load', initMap);

所以首先是变量,然后我从 dom 内的 div 的数据属性中获取国家名称和城市名称。然后我遍历地址以获得标记(和折线)的 lat/lng 值。 如果我 console.log 最后的 locations 变量,它在控制台中显示一个空数组,但是当我单击该数组时,该数组已被填充(可能导致该数组在显示后被填充)..

P.S。因为我还不能 post 图片,所以 console.log() 只显示 [ ] 当我点击数组时,它显示的对象很好...

0  Object { lat=53.3498053,  lng=-6.2603097}
1  Object { lat=53.3498053,  lng=-6.2603097}
2  Object { lat=53.3498053,  lng=-6.2603097}
3  Object { lat=53.717856,  lng=-6.3560985}
4  Object { lat=54.5982897,  lng=-5.8925882}
5  Object { lat=53.59944249999999,  lng=-7.850193999999999}
6  Object { lat=54.6541972,  lng=-8.110546}
7  Object { lat=54.9558392,  lng=-7.7342787}

非常感谢任何帮助,因为我从昨天开始就一直坚持这个...

尝试:

var count_getJSONs_done = 0;
for (var x = 0; x < addresses.length; x++) {

    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {

        var p = data.results[0].geometry.location;
        var latlng = new google.maps.LatLng(p.lat, p.lng);

        locations.push({lat: p.lat, lng: p.lng});

        marker = new google.maps.Marker({
            position: latlng,
            map: map
        });

        bounds.extend(marker.position);

    })
      .always(function() {
         count_getJSONs_done++;
         if (count_getJSONs_done == addresses.length) // the last getJSON in the loop is completed
           processLocations();
      });

}

根据 http://api.jquery.com/jquery.ajax/ 部分:"Callback Function Queues",.always 回调将在 getJSONsuccess 处理程序之后调用。

更新: 请注意,即使某些 getJSON 失败,此代码也能正常工作。

试试这个逻辑

for (var x = 0; x < addresses.length; x++) {

$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {

    var p = data.results[0].geometry.location;
    var latlng = new google.maps.LatLng(p.lat, p.lng);

    locations.push({lat: p.lat, lng: p.lng});

    marker = new google.maps.Marker({
        position: latlng,
        map: map
    });

    bounds.extend(marker.position);

    if(locations.length == addresses.length){ // all locations gathered
        console.dir(locations)
    }
});

}