如何使用Google地图JavaScript API V3获取距离

3

我正在尝试整理由谷歌地图生成的距离数组。我需要将我的列表按从近到远的顺序排序。我可以使用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
    }
}

正如代码中所注释的那样,我可以填充summaryPanel.innerHTML,但是当我填充数组trdistances时,警报会给我“未定义”。 这是一些新手javascript编码错误吗? 我阅读了关于变量范围的内容,这应该可以工作。 帮帮我,智者。


directionsService.route 的 for 循环之后尝试使用 alert(trdistances[0]);//debug 进行调试。 - KJYe.Name
谢谢 kj。是的,我已经尝试过了,它可以工作。我的问题是我需要在循环后访问信息,这就是为什么调试警报在那里的原因。一旦运行此循环,我想按照从用户位置到酒庄的距离对酒庄进行排序。 - Poolczar
你可以在全局范围内创建一个函数,在路由的回调函数中调用它并在其中执行逻辑。当你执行 alert(trdistances[0]) 却没有得到任何结果时,原因是回调函数尚未被调用,因此 trdistances[0] 中没有任何内容,所以你需要在回调返回后再调用该逻辑。 - KJYe.Name
Kjy,我认为你是对的。我正在探索这个问题,但我仍然无法从函数中获取信息。你能给我展示一个例子让我试一下吗?谢谢。 - Poolczar
@Poolczar 确定,等我想出一个小例子。 - KJYe.Name
@Poolczar,请看一下我的答案,看看它是否有效。 - KJYe.Name
1个回答

3
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);
}

问题是跟踪for循环的X的范围。基本上,您必须确保在获取trdistances的最终结果之前,所有回调都已完成。因此,您将不得不使用闭包来实现这一点。通过将第一个for循环的X存储到闭包中的index中,通过将X作为index传入,您可以检查回调是否是最后一个,如果是,则trdistances应该是您的最终结果。您的代码修改应该有效,但如果无效,请留下评论。
此外,我使用闭包标记了自己版本的Google地图,以解决在for循环中使用异步directionServices的问题,并且它起作用。这是我的演示jsfiddle。跟踪console.log()的输出以查看闭包中的X与index的差异。

我仍然无法在函数之外访问trdistances。它甚至不需要是trdistances,它可以是wineries中的另一个元素。目前,wineries具有酒庄名称、纬度和经度。使用纬度和经度,我正在通过方向服务计算用户与酒庄之间的距离。完成所有这些后,我需要按距离对整个数组进行排序,以便我可以显示“最近的酒庄'Bubbly bubbles'距离您所站立的位置0.5公里”。 - Poolczar
trdistances声明为全局变量,以便在所有函数外部进行声明。目前它是在calcDistances函数内部声明的,除非您创建一个全局函数来访问并将trdistances作为参数传递给该函数。请查看我的jsfiddle,并查看我如何设置变量。 - KJYe.Name
@Poolczar 请记住,如果您想访问 trdistances 或者您将其存储在 trdistanceswineries 中,请等待回调函数全部返回。 - KJYe.Name
你真是个天才。抱歉有些混乱,第一次运行时出了点问题。我想我的Apache服务器可能被破坏了。重启后,快速检查了一下代码,现在它已经可以正常工作了。谢谢。 - Poolczar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接