0

Can someone look at my code and tell me what I'm doing wrong? I understand that the Googlemaps geocoder is an async function so there needs to be a callback to handle the results. So I'm following the example here but I still can't get it to work:

How do I return a variable from Google Maps JavaScript geocoder callback?

I want to give my codeAddress function an actual address and a callback function. If the results array has something I send the lat and lng to the callback function.

  codeAddress = function(address, callback) {
    var gpsPosition = {};
    if (geocoder) {
      geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[0]) {
            console.log("got results!");
            var lat = results[0].geometry.location['B'];
            var lng = results[0].geometry.location['k'];
            callback(lat, lng);
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  };

This is the callback function. Basically it takes the lat and lng from the codeAddress function and puts the lat and lng into a hash and returns it. The idea is to then store the hash into a variable called location and reference location when I'm creating a new map marker.

  createGPSPosition = function(lat, lng){
    console.log("createGPSPosition called with lat and lng:");
    console.log(lat);
    console.log(lng);
    var gpsPosition = {};
    gpsPosition.B = lat;
    gpsPosition.k = lng;
    console.log("gpsPosition:");
    console.log(gpsPosition);
    return gpsPosition;
  };

When I run this code console.log(gpsPosition); actually logs the final hash object. But I still don't see the object getting returned... so when I do:

var stuff = codeAddress("1600 Amphitheatre Pkwy, Mountain View, CA 94043", createGPSPosition)

stuff still turns up as undefined. What's going on here?

Community
  • 1
  • 1
fuzzybabybunny
  • 5,146
  • 6
  • 32
  • 58
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – geocodezip Aug 31 '14 at 13:18

1 Answers1

0

This problem is that you're expecting asynchronous code to work in a synchronous way. stuff is defined before codeAddress finishes searching. The simplest solution is to provide a different callback, define stuff within that and use it there. This should work fine:

codeAddress("1600 Amphitheatre Pkwy, Mountain View, CA 94043", function(lat, lng){
   var stuff = createGPSPosition(lat, lng);
   console.log(stuff); // => your gpsPosition object
});

An alternative would be to learn Promises.

Richard Foster
  • 608
  • 3
  • 6