views:

45

answers:

2

So I'm making a Google Maps based webapp in JavaScript and a part of my code looks like this:

    function revGeocode(marker){ 
      var latlng = marker.position;
      if (geocoder) {
        geocoder.geocode({'latLng': latlng}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
              return "GOOD";
            } else {
              alert("No results found");
     return "BLAH1";
            }
          } else {
            alert("Geocoder failed due to: " + status);
      return "BLAH2";
          }
        });
      }
   else{
    return "No Geocoder?!"
   }
   return "Weird..";
  }

Now, for some reason it's skipping both the IF and ELSE conditions and jumping to the final return (which I just added to see why it wasn't catching both conditions). Anyone know why this is happening?

+1  A: 

If I'm right about what you're expecting to happen...

You're returning from the anonymous function when the geocoder receives a positive response from the Google Maps API service, but that returns from the anonymous function to the caller (whatever the geocoder object uses to dispatch notifications to your callback function), it doesn't return from your revGeocode(marker) method.

So, if you're expecting to see "GOOD" somewhere, that won't happen. If you put an alert("GOOD"); there instead, that should be triggered in a noticeable way. Currently, you should only see something if things don't go as planned, but it seems like things must be working out correctly.

After that, there are no other return statements in your initial function's codepath after your call to geocoder.geocode(), so the returned value will be "Weird..".

Hopefully that's helpful, if I've misunderstood what you were asking about, let me know.

Tim Stone
AWESOME :D thank you so much; both of you are awesome! Can't believe I made such a stupid mistake >_<
MapWeb
Is there any way I can get the results[1] so I can use it in another part of my code?
MapWeb
+1  A: 

the geocoder is an async process. Rather than returning "blah1 or blah2" in the inner function, have it call another function that does what you want.

Jonathan S.
Thank you so much!!!
MapWeb