Filippo oretti
Filippo oretti

Reputation: 49817

How can I print a variable returned from a function?

I have this function:

function findAddressViaGoogle(address){
     var geocoder = new google.maps.Geocoder();
     geocoder.geocode( { 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            return results[0].formatted_address;
        } else {
            console.log("Unable to find address: " + status);
        }
     });
}

How can I print the returned value from this function?

if i do:

$('#location-suggest').text('Do you mean <a>'+findAddressViaGoogle($(this).val())+'</a> ?');

it prints undefined

Upvotes: 0

Views: 170

Answers (3)

Zuul
Zuul

Reputation: 16269

The callback is being called somewhere inside the Geocoder() and its return value is not received inside your findAddressViaGoogle() function.

You can initialize a variable an pass the value to it:

function findAddressViaGoogle(address){
  var address = "";
  var geocoder = new google.maps.Geocoder();

  geocoder.geocode( { 'address': address }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      address = results[0].formatted_address;
    } else {
      console.log("Unable to find address: " + status);
    }
  });

  return address;
}

var myAddress = findAddressViaGoogle('foobar');
alert(myAddress);

Also, keep in mind that you have to call a function before it can return anything.

So to pass the collected value:

$('#myElementID').html(findAddressViaGoogle('foobar'));

Upvotes: 2

Daniil Ryzhkov
Daniil Ryzhkov

Reputation: 7596

Like this:

$(".putYourSelectorHere").html(findAddressViaGoogle())

replace .putYourSelectorHere with your selector (#output for example). If you want to print your result in the body use body selector:

$("body").html(findAddressViaGoogle())

http://api.jquery.com/html/

Upvotes: 2

Cole Tobin
Cole Tobin

Reputation: 9430

Are you looking for document.write?

Upvotes: 2

Related Questions