距离矩阵google maps javascript api3

| 我玩距离矩阵 http://code.google.com/apis/maps/documentation/javascript/services.html#distance_matrix 获得从一个起点到多个目的地的持续时间。 我有以下代码:
var duration = new Array();
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: destination,
        travelMode: google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false
    }, 
    function(response, status)
    {
        if (status == google.maps.DistanceMatrixStatus.OK)
        {
            var destinations = response.destinationAddresses;
            var results = response.rows[0].elements;

            for (var j = 0; j < results.length; j++)
                duration[j] = results[j].duration.value;
        }
    });
    alert(duration[0]);
但我有警报“未定义”。当我将alert命令放入回调函数中时,我得到了我想要的警报。这是为什么???我该如何解决? 预先谢谢你!     
已邀请:
var duration = new Array();
function calculate_distance(){
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: destination,
        travelMode: google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false
    }, 
    function(response, status)
    {
        if (status == google.maps.DistanceMatrixStatus.OK)
        {
            var destinations = response.destinationAddresses;
            var results = response.rows[0].elements;

            for (var j = 0; j < results.length; j++)
                duration[j] = results[j].duration.value;
        }
    });
}
google.maps.event.addListener(autocomplete, \'place_changed\', calculate_distance);
alert(duration[0]);
尝试类似的事情     
将警报移到回调中。该函数是异步执行的回调。     

要回复问题请先登录注册