Skip to content Skip to sidebar Skip to footer

Javascript Local And Global Variables Losing Scope In Callback Function

I have tried different variable scopes and none seem to work? My callback is getting a valid result but no matter the scope of the variable I assign it to I lose the value once the

Solution 1:

geocode is an asynchronous function, so when you call it, it immediately returns and the next lines are executed before the value of Lat is set. Think of it this way:

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

What you want to do is to actually read the value of Lat in the callback itself:

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);
    }


});

Solution 2:

I think Ameen has the right of it. Your element reference must be incorrect.

Try this:

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

or

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

Solution 3:

As Ameen said geocode is a asynch process so you need to put your alert & display code in callback function. and your another mistake is that you are using lat() & lng() as a method, its not a method its a property you just need to use it directly. so your code some look like.

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);
    }
});

Post a Comment for "Javascript Local And Global Variables Losing Scope In Callback Function"