推送到函数内的数组

时间:2013-05-21 14:46:34

标签: javascript arrays

我正在尝试为路由的起点/终点建立一个纬度和经度数组。

function parkRoute(){
    var start = $('#start').val();
    var end = $('#end').val();
    var points = [];
    function printPoints(points){
    console.log(points)
    }
    function getXY(add){
        geocoder.geocode( {'address': add + ", glendale, ca"}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0].geometry.location) {
                    var lon = results[0].geometry.location.kb;
                    var lat = results[0].geometry.location.jb;
                    points.push(lat,lon);
                    console.log(points)
                }
            }
        })          
    }
    getXY(start);
    getXY(end);
    printPoints(points);
}

它首先打印出一个空数组,即使我在创建数组的函数之后调用另一个函数来打印它们。

[]                                      parks1.js:192

[34.1480811, -118.24759369999998]               parks1.js:201

[34.1480811, -118.24759369999998, 34.1851925, -118.27651679999997] parks1.js:201

我做错了什么?

2 个答案:

答案 0 :(得分:9)

在推送之前打印数组内容。地理编码操作是异步的,因此您必须从异步回调中打印。

答案 1 :(得分:2)

问题是你没有等待所有异步的回调被执行。

你可以这样做:

var inProcess = 0; // number of tasks we're waiting for
function getXY(add){
    inProcess++; // increment the number of tasks
    geocoder.geocode( {'address': add + ", glendale, ca"}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0].geometry.location) {
                var lon = results[0].geometry.location.kb;
                var lat = results[0].geometry.location.jb;
                points.push(lat,lon);
                console.log(points)
            }
        }
        oneProcessIsDone();
    })          
}
function oneProcessIsDone() {
    if (--inProcess==0) { // decrement the number of tasks, and print the points if all are done
        printPoints(points);
    }
}
getXY(start);
getXY(end);