如何从Google maps javascript api v3获取距离

如何从Google maps javascript api v3获取距离,javascript,google-maps,closures,Javascript,Google Maps,Closures,我试图通过谷歌地图生成的一系列距离进行排序。我需要把我的名单排得最近最远。通过directionsService api示例,我可以获得显示的所有方向和距离,但我不知道如何在函数之外检索这些信息,以便对其进行排序 function calcDistances() { for (var x = 0; x < wineries.length; x++) { var winery = wineries[x]; var trdistances = [

我试图通过谷歌地图生成的一系列距离进行排序。我需要把我的名单排得最近最远。通过directionsService api示例,我可以获得显示的所有方向和距离,但我不知道如何在函数之外检索这些信息,以便对其进行排序

    function calcDistances() {
    for (var x = 0; x < wineries.length; x++) {
        var winery = wineries[x];
        var trdistances = [];       
        var request = {
            origin: map.getCenter(), 
            destination: new google.maps.LatLng(winery[1], winery[2]),
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };

        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                var route = response.routes[0];
                var summaryPanel = document.getElementById("tasting_rooms_panel");
                // For each route, display summary information.
                for (var i = 0; i < route.legs.length; i++) {
                    //this works fine and displays properly
                    summaryPanel.innerHTML += route.legs[i].distance.text;
                    //I want to store to this array so that I can sort
                    trdistances.push(route.legs[i].distance.text);
                }
            }
        });
        alert(trdistances[0]);//debug
    }
}
函数calcDistances(){
对于(var x=0;x
如代码中所述,我可以填充summaryPanel.innerHTML,但当我填充数组trdistance时,警报会显示“未定义”。这是一个新手javascript编码错误吗?我读了变量的范围,这应该行得通。帮助我,哦,聪明的人。

函数calcDistances(){
function calcDistances() {
    for (var x = 0; x < wineries.length; x++) {
        var winery = wineries[x];
        var trdistances = [];       
        var request = {
            origin: map.getCenter(), 
            destination: new google.maps.LatLng(winery[1], winery[2]),
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };

        //Using Closure to get the right X and store it in index
        (function(index){
               directionsService.route(request, function(response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                         var route = response.routes[0];
                         var summaryPanel = document.getElementById("tasting_rooms_panel");
                         // For each route, display summary information.
                         for (var i = 0; i < route.legs.length; i++) {
                              //this works fine and displays properly
                              summaryPanel.innerHTML += route.legs[i].distance.text;
                              //I want to store to this array so that I can sort
                              trdistances.push(route.legs[i].distance.text);
                         }

                         if(index == wineries.length-1){  //check to see if this is the last x callback
                              console.log(trdistances); //this should print the result 
                              //or in your case you can create  global function that gets called here like sortMahDistance(trdistances); where the function does what you want.
                              printMyDistances(trdistances); //calls global function and prints out content of trdistances console.log();
                         }
                    }
               });
        })(x);  //pass x into closure as index
    }
}

//on global scope
function printMyDistances(myArray){
     console.log(myArray);
}
对于(var x=0;x
问题在于跟踪for循环的
X
的范围。基本上,您必须确保在获得trdistance的最终结果之前完成所有回调。所以,您必须使用闭包来实现这一点。通过在as
index
中传递
X
,将for循环的第一个“
X
存储到闭包中的
index
,您可以检查回调是否是最后一个,如果是,则您的
trdistance
应该是最终结果。你的代码的这个模块应该可以工作,但如果不能,请留下评论


此外,我在for循环中使用闭包标记了我自己版本的GoogleMap,并使用异步directionServices进行解析,结果成功了。这是我的演示。跟踪
console.log()的输出查看关闭内的
X
vs
index

尝试
alert(trdistance[0])//在
directionservice.route中的for循环之后进行调试。是的,我试过了,效果不错。我的问题是,我需要在循环之后访问信息,这就是为什么调试警报会出现在它所在的位置。一旦运行了这个循环,我想根据酿酒厂与用户位置的距离来订购酿酒厂。您可以在全局范围内创建一个函数,在route的回调函数中调用该函数,并在那里执行逻辑。当你发出
警报(trdistance[0])
但什么也没有得到的原因是因为回调函数还没有被调用,因此,
trdistance[0]
中没有任何内容,所以你想在回调返回后调用逻辑。Kjy,我想你是对的。我现在正在探索,但是从函数中获取信息仍然有问题。你能给我举个我可以试试的例子吗?Thanks@Poolczar当然,请给我一点时间,让我制定一个小示例,我仍然无法访问函数之外的trdistance。它甚至不需要被过滤,它可以是酿酒厂的另一个元素。目前,酿酒厂有一个酿酒厂的名字,拉坦朗。使用lat和long,我通过方向服务计算与用户的距离。一旦所有这些都完成了,我需要按距离订购整个阵列,这样我就可以显示“离w.5公里最近的酿酒厂‘泡泡’