从 Google Maps API 中的 GEvent.addListener 返回值?

tri*_*nth 5 javascript google-maps

我只是想使用 Google Maps API 从地图上的 2 个点获取距离。使用 GDirections。问题是函数完成后,距离始终为空。我知道这是因为直到函数完成后才会调用“加载”事件。事件侦听器也不返回值,所以我很难过!

有人知道如何让这个函数返回距离吗?也许有更好的方法来获取 Google Maps API 中两点之间的距离?

function getDistance(fromAddr, toAddr) {    
var distance;
var directions;

directions = new GDirections(null, null);
directions.load("from: " + fromAddr + " to: " + toAddr);

GEvent.addListener(directions, "load", function() {
    distance = directions.getDistance().html;
    distance = distance.replace(/&.*/, '');
});

return distance; //outputs null
}
Run Code Online (Sandbox Code Playgroud)

Red*_*ing 3

GDirections 加载是异步的。在加载事件被触发之前,您将无法使用加载请求的结果。这意味着您的getDistance函数只是设置GDirections 加载请求,它无法同步(立即)获取请求的结果。GDIRECTIONS对象必须离开并向 Google 发出 HTTP 请求以便它可以计算出两点之间的距离。

您需要做的是将使用距离的代码放入传递给加载请求的回调函数中:

GEvent.addListener(directions, "load", function() {
            // this is a callback function that is called after 
            // the getDistance function finishes.
            var distance = directions.getDistance().html;

            // Have a distance now, need to do something with it.
            doSomethingWithTheDistanceWeGotBack (distance);
    });
Run Code Online (Sandbox Code Playgroud)

下面是使用GDirections加载的例子(获取的是行驶时长,不是距离,但原理是一样的):

http://www.cannonade.net/geo.php?test=geo6

您可以在这里找到来源:

http://www.cannonade.net/geo6.js