0

I have this code and problem is that it alerts "undefined". How can I make alert (add); wait for geocoder? (I don't want to use alert (add); in function codeAdd)

<script>

function codeAdd(address){
var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    return latitude;
  } 
}); }

var add = codeAdd("new york");
alert (add);



</script>
</body>
</html>

2 Answers2

0

The problem you have is that the geoencode is async so it's carrying on to your alert before the results have returned.

You need to put your alert inside the async callback. In other words the alert (which depends on the data returned) needs to be performed once the lookup has been completed.

// some calling code
function onLoad(){
  codeAdd("new york");
}



// the function
function codeAdd(address){
var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();

    // we've got the details, show the alert
    alert (latitude);
  } 
}); 
}
Liath
  • 9,913
  • 9
  • 51
  • 81
0

As you don't return anythin with codeAdd function, there is no need to do :

 var add = codeAdd("new york");

but juste

codeAdd("new york");

And you can use the callback function of geocode :

geocoder.geocode({ 
    'address': address
}, function (results, status) {
    alert(results);
    //here the code to execute once geocode is loaded
});
BastienSander
  • 1,718
  • 4
  • 24
  • 50