Pregunta

I'm getting crazy with this.

        geocoder.geocode( { 'address': address}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            latitude = results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
            locations[j][0] = direcciones[j]['1'];
            locations[j][1] = latitude;
            locations[j][2] = longitude;
            locations[j][3] = direcciones[j]['10'];
            j++;

        } 
        }); 

If I do an alert of locations[0][0] inside geocode function, it works fine, but if I do it out, i get the previous value, because I am not modifying global locations variable...

Someone could help me to chenge correctly that variable?

¿Fue útil?

Solución

...but if I do it out, i get the previous value, because I am not modifying global locations variable...

Yes, it is, it's just doing it later. The call to geocode is asynchronous, and so won't see the result until the callback is made. Code immediately after the geocode function call will run before the callback runs, and so you won't see any change.

Let's use a simpler example for illustration:

// A variable we'll change
var x = 1;

// Do something asynchronous; we'll use `setTimeout` but `geocode` is asynchronous as well
setTimeout(function() {
    // Change the value
    x = 2;
    console.log(Date.now() + ": x = " + x + " (in callback)");
}, 10);
console.log(Date.now() + ": x = " + x + " (immediately after setTimeout call)");

If you run that (fiddle), you'll see something like this:

1400063937865: x = 1 (immediately after setTimeout call)
1400063937915: x = 2 (in callback)

Note what happened first.

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