0

There are so many threads about this topic but I still haven't been able to find a suitable answer for my case...

Here is what I'm trying to do:

1) define a function to get geocodes with Google Maps API v3

2) call the function with the address in question in order to get the geocode for this particular address

The code works perfectly fine if I place

    alert(address); 

after

    address = results[0].geometry.location;

As I need it as a global variable, this is unfortunately not an option. When trying to use the 'address' variable as a global function, I always get as value 'undefined'.

<!DOCTYPE html>
<html>
<head>
  <script src="http://maps.googleapis.com/maps/api/js?sensor=false"
      type="text/javascript"></script>
</head>

  <script type="text/javascript">
    var geocoder;
    var address;

     address = 'Frankfurt, Germany';

  function codeAddress() {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {

address = results[0].geometry.location;


  } else {
    alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

codeAddress(address);
alert(address);

  </script>


</body>
</html>

Anybody able to help me with this? Staring at the code doesn't seem to get me anywhere. I appreciate all help available, thanks!!!

Kleni
  • 3
  • 4
  • possible duplicate of [Why my geocode cannot show the address](http://stackoverflow.com/questions/11482800/why-my-geocode-cannot-show-the-address) – geocodezip May 13 '13 at 21:35

2 Answers2

0

The problem is that geocode is asynchronous, no?

That means that the geocode callback is invoked "at some point later" which is after the outside alter in the original post is first called. (It should not alert undefined as it is first set to a particular string, so I'm ignore that statement.)

function codeAddress() {
  geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      // Only use address *after the callback success* and get rid of
      // the global variable if possible - note how it's just passed here.
      // You can use `debugger;` to stop here and check the value to
      // make sure it is set as appropriate.
      var address = results[0].geometry.location;
      alert(address);
      doOtherStuffWithAddress(address);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

function doOtherStuffWithAddress (address) {
   // don't need no stinking globals
}

See How to return the response from an AJAX call?:

The A in AJAX stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.

And specialized for context:

The geocode function is asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, geocode returns immediately and the next statement, alert(address), is executed before the function you passed as success callback was even called.

Community
  • 1
  • 1
user2246674
  • 7,621
  • 25
  • 28
  • Thanks very much for your answer. It has definitely taken me at least 2 steps forward. Unfortunately I'm still stuck with this, as I don't get the address output to the 'doOtherStuffWithAddress' fuction. – Kleni May 15 '13 at 08:21
  • @Kleni Verify that the data obtains is as expected - use `debugger;` to attach a breakpoint (works well in Firebug/Firefox and Chrome, and is annoying to use in IE). Then look to make sure `results[0].geometry.location;` contains the expected value, if not, find out why :D If it *does* contain the expected value, do the same check in the appropriate function that was called (e.g. `doOther..`) and keep working until the exact location the unexpected data is encountered. – user2246674 May 15 '13 at 21:29
0

Thanks guys for your answers. I was now able to finalize my project!!! Find my final code below. The code populates the geocodes for an array of addresses. Have fun.

<!DOCTYPE html>
<html>
<head>
  <script src="http://maps.googleapis.com/maps/api/js?sensor=false"
          type="text/javascript"></script>
</head>
<BODY>
<DIV ID="pro"></div>
<DIV ID="adr"></div>

  <script type="text/javascript">
    var geocoder;




var addresses = "Berlin, Deutschland; Frankfurt, Deutschland; Broadway Street, New York City, New York, USA";


 geocoder = new google.maps.Geocoder();

var address = addresses.split(';');

var i = 0;
var timeout = 600;


codeAddress(i);


function codeAddress(i) {


    geocoder.geocode( { 'address': address[i]}, function(results, status) 
    {
            if (status == google.maps.GeocoderStatus.OK) {
            document.getElementById("adr").innerHTML = document.getElementById("adr").innerHTML + "<BR>{location: new google.maps.LatLng" + results[0].geometry.location + ", weight: 1},";

                                } else {
                if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
                    {
                        setTimeout(function() { addMarker(position); }, (timeout * 3));
                    }
                                        }


i++;
var percent = ((i) / address.length) * 100;
percent = percent.toFixed(2);
percent = percent + " %";
document.getElementById("pro").innerHTML = percent; 


if (i < address.length)
        {
            setTimeout(function() { codeAddress(i); }, (timeout));
         }

    });



            }

</script>


</body>
</html>
Kleni
  • 3
  • 4