Pregunta

I can't access the variable outside the function in JavaScript.

JavaScript code:

 var latitude;
 var longitude;
 function hello()
   {
   for(var i=0;i<con.length;i++)
   {
   geocoder.geocode( { 'address': con[i]}, function(results, status) 
   {

        if (status == google.maps.GeocoderStatus.OK)
        {
            latitude=results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
        });
         alert(latitude);    //here it works well
   }
   }
   alert(latitude);      //here i am getting error: undefined

How can I use the variable outside the function?

¿Fue útil?

Solución

This is because you try to output variables before you get result from the server (geocode is async function). It is wrong way. You only can use them in geocode function:

geocoder.geocode( { 'address': con[i]}, function(results, status)  {
    if (status == google.maps.GeocoderStatus.OK) {
        latitude=results[0].geometry.location.lat();
        longitude = results[0].geometry.location.lng();
    }
    <--- there
});

Or you can use callback function:

var latitude;
var longitude;

function showResults(latitude, longitude) {
    alert('latitude is '+latitude);
    alert('longitude is '+longitude);
}

function hello()
{
    for(var i=0;i<con.length;i++)
    {
        geocoder.geocode( { 'address': con[i]}, function(results, status)  {
            if (status == google.maps.GeocoderStatus.OK) {
                latitude=results[0].geometry.location.lat();
                longitude = results[0].geometry.location.lng();
            }
            alert(latitude);    //here it works well
            showResults(latitude, longitude);
        });
    }
}

But it is same.

Also, it looks like you have some mistakes with format. I updated code a bit. Now brackets ) and } are in correct place. Correct me if I am wrong.

Anyway, it is good practise to format your code. I was thinking about your brackets about 2 minutes. You have to use correct format.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top