-1

I have this javascript function which geocodes a LatLng object:

function geolocate_table(location)
{
  geocoder.geocode({'latLng': location}, function(results, status){
    if( status == google.maps.GeocoderStatus.OK){
      if(results[0])
      {
        console.log(results[0].formatted_address);
        return(results[0].formatted_address);
      }
      else
        return("Non disponibile");
    }
    else
    {
      return("jasand");
    }
  });
}

My problem is that if I call the function from another one (e.g.:

function test(latlng)
{
  var street;
  street=geolocate_table(latlng);
  console.log(street);
}

The console log of test will give me "undefined" even if the original value in geolocate_table is correctly evaluated and logged in the console. Am i doing something wrong? Thank you in advance for your answers :)

Greg
  • 18,111
  • 5
  • 46
  • 68
Stefano Kira
  • 175
  • 2
  • 3
  • 16

1 Answers1

0

You probably want to use a callback in this instance:

function geolocate_table(location, callback)
{
     //do stuff, but for every return you would have
     //something like
     if (typeof callback == 'undefined') return whatever;
     else return callback(whatever);
}

function test(latlng)
{
   var street;
   street=geolocate_table(latlng, function() { console.log(street); });
}

You do this because the geocoder is asynchronous - it will continue execution of the rest of the program while it waits. With a callback you give it the next set of instructions to do after it completes the aynchronous part.

dave
  • 62,300
  • 5
  • 72
  • 93