Javascript 谷歌地图地理编码器,计算距离,

Javascript 谷歌地图地理编码器,计算距离,,javascript,google-maps,asynchronous,Javascript,Google Maps,Asynchronous,我正在计算到地址之间的距离 var geocode = function(start, end) { geocoder.geocode({'address': start}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { //In this case it creates a marker, but you can get the lat and

我正在计算到地址之间的距离

var geocode = function(start, end) {
    geocoder.geocode({'address': start}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter(results[0].geometry.location);
            document.getElementById('startLatlng').value = results[0].geometry.location;
        }
    });
    geocoder.geocode({'address': end}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter(results[0].geometry.location);
            document.getElementById('endLatlng').value = results[0].geometry.location;
        }
    });
   }
   ...
   ...
   google.maps.geometry.spherical.computeDistanceBetween(document.getElementById('startLatlng').value, document.getElementById('endLatlng').value) // error
   alert(document.getElementById('startLatlng').value) // empty
   alert(document.getElementById('endLatlng').value) // empty
我还尝试使用回调来设置这样的全局变量

var startl
var endl
var geocode = function(start, end, callback, callback2) {
    // ....
    callback(results[0].geometry.location)
    // ....
    callback2(results[0].geometry.location)
}

function setstart(value)
    startl = value

function setend(value)
    endl = value

....
....

geocode(origin, destination)

alert(startl) // undefined
alert(endl) // undefined

google.maps.geometry.spherical.computeDistanceBetween(startl, endl) // error
问题是我需要这两个结果来计算距离

我试图使用
setTimeout
来等待异步调用像这样完成

var startl
var endl
var geocode = function(start, end, callback, callback2) {
    // ....
    callback(results[0].geometry.location)
    // ....
    callback2(results[0].geometry.location)
}

function setstart(value)
    startl = value

function setend(value)
    endl = value

....
....

geocode(origin, destination)

alert(startl) // undefined
alert(endl) // undefined

google.maps.geometry.spherical.computeDistanceBetween(startl, endl) // error

但是什么也没发生

用地理编码器代替

可能的重复