-1

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;
}
  • 1
    The geocoder is asynchronous. You can't return anything from an asynchronous callback fiction. You need to use the response inside the callback function where/when it is available. – geocodezip Dec 28 '15 at 21:35
  • and how do I get to work – Alberto Setim Dec 28 '15 at 21:37
  • @geocodezip that's precisely what OP does. They exploit the result of the geocoding in a callback `function(result,status)`. @Alberto you have a typo in your variable `latLong` --> `latLng` – Jeremy Thille Dec 28 '15 at 21:41
  • The `return results[0].formatted_address` is inside the callback function. – geocodezip Dec 28 '15 at 21:45
  • Yes, so? Isn't that how it's supposed to be? Edit : ok I get what you mean. You can't RETURN anything from a callback function, indeed. – Jeremy Thille Dec 28 '15 at 21:50

1 Answers1

1

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);
}
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63