Search code examples
javascriptgoogle-mapsgeocode

results[0].formatted_address return undefined or null


i am trying to get adress by a function where i just have to give latLong but i am with a real problem to save de value to return or return it simple

function getadress(latLong){
  var adress ="";
  geocoder.geocode( {'latLng': latLng},
  function(results, status) {
    if(status == google.maps.GeocoderStatus.OK) {
      if(results[0]) {
        adress = results[0].formatted_address; // wrong way result empty
        alert(results[0].formatted_address); // result perfect adress
        return results[0].formatted_address // result undefiened
      }
      else {
        adress = "No results";
      }
    }
    else {
      adress = status;
    }
  });
  return adress;
}


Solution

  • Javascript being asynchronous, if you write it this way, the returned address will always be empty. Here is the execution order of your current code :

    function getadress(latLng){
    
      var adress =""; // (1) Sets address as empty.
    
      geocoder.geocode( {'latLng': latLng}, // (2) Launches the geocoding request.
          function(results, status) { // (4) later, when the result gets back, populates the address.
              adress = results[0].formatted_address;
          });
      });
    
      return adress; // (3) Immediately returns an empty address.
    }
    

    How you should architecture it :

    function getadress(latLng){
    
      var adress =""; // (1) Sets address as empty.
    
      geocoder.geocode( {'latLng': latLng}, // (2) Launches the geocoding request.
          function(results, status) { // (3) later, when the result gets back, populates the address.
              adress = results[0].formatted_address;
              nextStep(address);
          });
      });
    }
    
    function nextStep(address){ // (4) should log the address
       console.log(address);
    }