Javascript Google Maps API中GEvent.addListener的返回值?
我只是想用谷歌地图API从地图上的两个点得到距离。使用GDirections。问题是函数完成后,距离始终为空。我知道这是因为函数完成后才调用“load”事件。事件侦听器也不返回值,所以我被难住了 有人知道如何让这个函数返回距离吗?也许有更好的方法在谷歌地图API中获得两点之间的距离Javascript Google Maps API中GEvent.addListener的返回值?,javascript,google-maps,Javascript,Google Maps,我只是想用谷歌地图API从地图上的两个点得到距离。使用GDirections。问题是函数完成后,距离始终为空。我知道这是因为函数完成后才调用“load”事件。事件侦听器也不返回值,所以我被难住了 有人知道如何让这个函数返回距离吗?也许有更好的方法在谷歌地图API中获得两点之间的距离 function getDistance(fromAddr, toAddr) { var distance; var directions; directions = new GDirections(nul
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
}
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);
});
以下是使用GDDirections负载的示例(获取驾驶持续时间,而不是距离,但原理相同):
您可以在此处找到来源: