Javascript 为什么这个函数调用会破坏程序并导致未定义的变量?

Javascript 为什么这个函数调用会破坏程序并导致未定义的变量?,javascript,google-maps,variables,undefined,Javascript,Google Maps,Variables,Undefined,我在另一个函数中使用这个javascript函数,从作为地址的字符串中获取纬度/经度值。该警报显示转换已成功,但如果调用该方法,则会出现javascript错误,表示该方法仍未定义 function getLatLng(address) { geocoder.geocode({ 'address' : address }, function(results, status) { if (status == google.maps.GeocoderS

我在另一个函数中使用这个javascript函数,从作为地址的字符串中获取纬度/经度值。该警报显示转换已成功,但如果调用该方法,则会出现javascript错误,表示该方法仍未定义

function getLatLng(address) {
    geocoder.geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert("Aus getLatLng: adresse:"+address+"Ergebnis: "+results[0].geometry.location);
            return results[0].geometry.location;
        } else {
            alert("Geocode was not successful for the following reason: "
                    + status);
        }
    });
}
我错过了什么?警报始终显示未定义的变量。为什么呢?
我什么都试过了。在我调用函数getLatLng之前,一切都很顺利。返回的某些内容不起作用:(

您的
getLatLng
函数实际上没有返回任何内容,这就是为什么
start
未定义的原因

function getLatLng(address) {
    geocoder.geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert("Aus getLatLng: adresse:"+address+"Ergebnis: "+results[0].geometry.location);
            return results[0].geometry.location;
        } else {
            alert("Geocode was not successful for the following reason: "
                    + status);
        }
    });
}
您编写的return语句包含在传递给
geocoder.geocode
的匿名函数中,因此它实际上不会从外部函数返回

由于
geocoder.geocode
是异步的,因此您将无法编写以这种方式返回结果的
getLatLng
,而是需要将回调函数作为参数传递,并在geocode API返回值时调用此函数,例如:

    var start = document.getElementById("route_start").value;
    start = getLatLng(start);
    alert("Start: "+start);

getLatLng
不返回任何内容…如上所述-它不返回任何内容-它是异步的