当推动所有标记完成后,如何使此函数返回整个数组?
function XTW_getLocations(data, div_id, map) {
var markers = [];
var marker;
var latLngBounds = new google.maps.LatLngBounds();
$(div_id).empty();
$.getJSON('GetLocations', "country=" + data.id,
function(data){
$.each(data, function(index, data) {
latLngBounds.extend(new google.maps.LatLng(data.location.latitude, data.location.longitude));
$(div_id).append( new Option(data.name, data.id ) );
marker = createMarker(data, icon, html, map);
markers.push(marker);
});
map.fitBounds(latLngBounds);
});
return markers;
}
答案 0 :(得分:2)
你不能返回它,因为它是异步的(它会在响应返回后填充,在函数已经返回之后)。
然而,您可以将其用于其他内容,例如:在准备好/填充时将其传递给另一个函数,如下所示:
function XTW_getLocations(data, div_id, map) {
var markers = [];
var marker;
var latLngBounds = new google.maps.LatLngBounds();
$(div_id).empty();
$.getJSON('GetLocations', "country=" + data.id,
function(data){
$.each(data, function(index, data) {
latLngBounds.extend(new google.maps.LatLng(data.location.latitude, data.location.longitude));
$(div_id).append( new Option(data.name, data.id ) );
marker = createMarker(data, icon, html, map);
markers.push(marker);
});
anotherFunction(markers);
map.fitBounds(latLngBounds);
});
}
答案 1 :(得分:1)
你不这样做,AJAX查询(getJSON
)是异步的,这意味着一旦你发出呼叫你就没有正常的处理顺序,你就像使用callBack一样致电getJSON
时:
function XTW_getLocations(data, div_id, map, callBack) {
var markers = [];
var marker;
var latLngBounds = new google.maps.LatLngBounds();
$(div_id).empty();
$.getJSON('GetLocations', "country=" + data.id,
function(data){
$.each(data, function(index, data) {
latLngBounds.extend(new google.maps.LatLng(data.location.latitude, data.location.longitude));
$(div_id).append( new Option(data.name, data.id ) );
marker = createMarker(data, icon, html, map);
markers.push(marker);
});
map.fitBounds(latLngBounds);
callBack(markers); //Callback goes here
});
//return markers;
}
现在,在致电XTW_getLocations
时,您需要为您的通话添加回调:
XTW_getLocations({some:'data'},'#map','map.png',function(markers){
//Handle markers here
})