简体   繁体   中英

Google Maps API — Why isn't this working?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM