Reputation: 49817
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
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
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())
Upvotes: 2