Javascript 局部和全局变量在回调函数中失去作用域



>我尝试了不同的变量作用域,但似乎都没有工作?我的回调得到了一个有效的结果,但无论我将其分配给的变量的范围如何,一旦回调结束,我就会丢失该值?

var geocoder;
var Lat;
var Long;
function codeAddress()
{

    var geocoder = new google.maps.Geocoder();
    var addy1......
    geocoder.geocode({ 'address': fullAddress }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK)
        {
            Lat = results[0].geometry.location.lat();
            Long = results[0].geometry.location.lng();
        }
        else
        {
            alert("Geocode was not successful for the following reason: " + status);
        }

    });
    alert(Lat);
    document.getElementById("Address_AddyLat").type.value = Lat;
    document.getElementById("Address_AddyLong").value = Long;
}

感谢您的投入。

geocode是一个

异步函数,因此当您调用它时,它会立即返回,并在设置Lat值之前执行下一行。可以这样想:

geocoder.geocode({ 'address': fullAddress }, /*...*/); // 1
alert(Lat); // 2
document.getElementById("Address_AddyLat").type.value = Lat; // 3
document.getElementById("Address_AddyLong").value = Long; // 4

你要做的是在回调本身中实际读取Lat的值:

geocoder.geocode({ 'address': fullAddress }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK)
    {
        Lat = results[0].geometry.location.lat();
        Long = results[0].geometry.location.lng();
        alert(Lat);
        document.getElementById("Address_AddyLat").type.value = Lat;
        document.getElementById("Address_AddyLong").value = Long;
    }
    else
    {
        alert("Geocode was not successful for the following reason: " + status);
    }

});

我认为阿明有权利。元素引用必须不正确。

试试这个:

document.getElementById("Address_AddyLat").value = Lat;

document.getElementById("Address_AddyLat").setAttribute("value",Lat);

正如Ameen所说,地理编码是一个异步过程,因此您需要将警报和显示代码放在回调函数中。 你的另一个错误是你使用lat()和lng()作为一个方法,它不是一个方法,它是一个属性,你只需要直接使用它。 所以你的代码有些看起来像。

geocoder.geocode({ 'address': fullAddress }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK)
    {
        Lat = results[0].geometry.location.lat;
        Long = results[0].geometry.location.lng;
        alert(Lat);
        document.getElementById("Address_AddyLat").value = Lat;
        document.getElementById("Address_AddyLong").value = Long;
    }
    else
    {
        alert("Geocode was not successful for the following reason: " + status);
    }
});

最新更新