-2

I am trying to get address info for my project. I can see the address by alert() method if i write it inside the geocode function. but if i outside of the function, it returns undefined.

tried to write the variable name like window.adres but didnt work. i think because of an another function with is parent of this.

how to make that variable global and change the value?

var geocoder = new google.maps.Geocoder;
var adres;

 var latlng = {lat: parseFloat(lat), lng: parseFloat(lon)};
    geocoder.geocode({'location': latlng}, function(results, status) {
      if (status === 'OK') {
        if (results[0]) {
         adres = results[0].formatted_address;
         //window.adres = ... is not working. i think because of an another function which is parent of these lines.
          alert(adres); //returns address   
        } 
      } else {
        window.alert('Geocoder failed due to: ' + status);
      }

 alert(adres); //returns undefined

also i tried that

var geocoder = new google.maps.Geocoder;


 var latlng = {lat: parseFloat(lat), lng: parseFloat(lon)};
    var adres = geocoder.geocode({'location': latlng}, function(results, status) {
      if (status === 'OK') {
        if (results[0]) {
         return results[0].formatted_address;

        } 
      } else {
        window.alert('Geocoder failed due to: ' + status);
      }

 alert(adres); //returns undefined too
gks
  • 1
  • 4

2 Answers2

1

If you set a global variable with window dot whatever, you will be able to get to it later by calling the same (fully qualified) variable.

Here is an example that proves this (run the snippet to see it in action).

function setVarInFunction(){
  window.adres = 'here is some text';
}
console.log(window.adres); // should be undefined
setVarInFunction();
console.log(window.adres); // now there should be something

The reason alert(adres) is not working the way you expect is that:

  • you create a variable at the beginning
  • you execute an asynchronous request off to Google to do some work, and update your variable when it comes back from Google
  • you execute your alert to show the var value, but you have no guarantee that Google has actually responded yet with it's data (it almost certainly has not yet responded)

What do you want to do with that value? You almost certainly don't want to just alert() it, right? Whatever you want to do with it, you should do in the block where it comes back from Google with success or failure.

Jonathan
  • 4,916
  • 2
  • 20
  • 37
0
  1. You are missing the ending of your anonymous function.
  2. This is an issue related to the callbacks in javascript.

Geocoder takes time to process your request. Thus, you alert address while it is not yet defined.

I have updated your code to new coding standards and added comments :

let geocoder = new google.maps.Geocoder;
let latlng = { lat: parseFloat(lat), lng: parseFloat(lon) };
let address = null;

// 1. The geocoder starts the process to find the address
geocoder.geocode({'location': latlng}, (results, status) => {
    // 3. The geocoder finally located the address, because it takes time.
    if (status === 'OK') {
        if (results[0]) {
            // This updated the variable with the correct result.
            address = results[0].formatted_address;
            // You should call here a new function, in order to do the rest of your work
        }
    } else {
        window.alert('Geocoder failed due to: ' + status);
    }
});

// 2. you output address
alert(address); // This won't work as address is set by the geocoder which is asynchronous

Hope this helps.

LeNiglo
  • 71
  • 8
  • This probably won't help because it won't work... – MrUpsidown Feb 20 '19 at 00:01
  • @MrUpsidown Why won't this work ? works fine on my side. The point of the code was to illustrate how the callbacks actually work. – LeNiglo Feb 21 '19 at 01:09
  • Right. I didn't read your answer well... I just read the code and that code won't work. Your explanation is more or less correct though. For a good and quality answer you could have given a solution and not provide non-working code... – MrUpsidown Feb 21 '19 at 09:16