How do I return a variable from Google Maps JavaScript geocoder callback?
You can't return the value from the function, the value doesn't exist yet when the function returns.
The geocode
method makes an asynchonous call and uses a callback to handle the result, so you have to do the same in the codeLatLng
function:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
codeLatLng(function(addr){
alert(addr);
});
}
function codeLatLng(callback) {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
callback(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
Return value with google maps geocoder
You have to move "alert(locationName);" into the geocoder.geocode callback. Because geocoder.geocode executes an AJAX request. When you throw the alert the var locationName is still undefined (not set).
Try it like this
function getLocationName(latitude, longitude, callback) {
if (isNaN(parseFloat(latitude)) || isNaN(parseFloat(longitude))) {
return false;
}
var locationName;
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude)
// Reverse Geocoding using google maps api.
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
locationName = results[1].formatted_address;
alert(locationName);
}
else {
locationName = "Unknown";
}
}
else {
locationName = "Couldn't find location. Error code: " + status;
}
alert(locationName);
callback(locationName);
});
}
To get the "return" you have to create a your own callback.
Try like this
$("#id").on("event", function (event, ui) {
getLocationName(latitude, longitude, function(result){
$("#userLocation").text(result);
});
});
As for the alert, the return is called before the ajax request. So you have to use a callback to be called when the ajax request has done his job!
Returning value from a google maps callback function
That's because geocode()
is asynchronous: it returns immediately but the callback function is invoked as soon as the response arrives. You need to accept a callback in get_val()
and pass the value to this method instead of trying to return it (it's impossible):
function get_val(latlng, cb) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
cb(results[0].address_components[i].long_name);
});
}
Usage:
get_value(latlng, function(longName) {
/* do something */
});
Google reverse geocode return variable
You are having an issue with understanding the asynchronous capabilities of javascript and callback functions
geocoder.geocode function accepts a callback function as it's 2nd parameter. This function will be called asynchronously whenever the address is retrieved.
Your console.log at the end will not work because after the geocoder.geocode() function has been called, the program will not wait for the callback function to be called and rather immediately executes the next instructions. In this case address1 variable will not have been populated yet.
What you are actually looking for is a function that accepts your location and a callback function. Something like this:
function getAddress(location, callback){
geocoder.geocode({'latLng': location}, function(results, status){
if(status === google.maps.GeocoderStatus.OK){
if(results[0]){
var address1 = results[0].formatted_address;
callback(address1);
}
}
});
}
Now from the other file which you want to use this address in, you can call this function like this:
var location = new google.maps.LatLng(latitude, longitude);
getAddress(location, function(address)
{
console.log(address);
});
And here, after the address has been retrieved, your function that you have defined accepting the address will be called and the address variable will be available to you.
Using a callback function with Google Geocode
Your problem is, that you didn't connect the callback to the return. As the geocode()
function itself is already asynchronous, the return
doesn't have any effect there. Instead you have to pass the values you are returning here directly to the callback-function. Like this:
function getLocationData(position, callback) {
geocoder = new google.maps.Geocoder();
var location = 'Billings,MT';
if( geocoder ) {
geocoder.geocode({ 'address': location }, function (results, status) {
if( status == google.maps.GeocoderStatus.OK ) {
callback(results[0]);
}
});
}
}
How to store address from geocoder.geocode() in GeocoderService and return it to app.component?
1)
function(addr){
this.loc = addr; // <= here i can't store address it is undefined
alert(addr);
return this.loc;
}
this function is a callback function so you cannot return data from a callback function The reason why you have undefined loc variable, is because "This" of app component class has been shadowed by the "This" of the function so to resolve this issue you have to use the arrow function (but it does not resolve your problem)
this.codeLatLng(addr=> this.loc = addr);
2)
this.loc = this.geocoderService.initialize();
you will never get a value because initialize does not return a value
3) So what you have to do
Since the result of codeLatLng is asynchronous try to use Subject Or Observable object and in the app component subsribe to this object
Related Topics
Mixing Jsf El in a JavaScript File
Vue.Js - How to Properly Watch for Nested Data
Ruby on Rails 3.1 - Assets Pipeline - Assets Rendered Twice
Set Default Value of JavaScript Object Attributes
Console.Log() After Setstate() Doesn't Return the Updated State
How to Pause a Youtube Player When Hiding the Iframe
Difference Between Date(Datestring) and New Date(Datestring)
Maintain Model of Scope When Changing Between Views in Angularjs
Clear Text Selection with JavaScript
How to Trigger Jquery Change Event in Code
How to Include Newlines in Labels in D3 Charts
This' Different Between Repl and Script
Understanding Asynchronous Code in Layman's Terms
Can Jquery .Keypress() Detect More Than One Key at the Same Time
React - User-Defined Jsx Components Not Rendering
How to Tell If a <Script> Tag Failed to Load