Search code examples
javascriptfunctiongoogle-maps-api-3pass-by-referencehidden-variables

Assigning hidden variable in a function within a function


I have javascript code similar to the following, however when I try to use 'myVar' within foo(), its value is undefined. I've also tried passing the variable into bar() and assigning it directly, but will not pass by reference.

function foo() { 
   bar();
   var myVar = document.getElementById('coords').value;
   // myVar should now be (40.7143528, -74.0059731)
   alert(myVar); // returns blank

   var request = {
    location: myVar,
    radius: 500,
    types: [type] //previously defined 
   };

   //Then send a search request to Google...
}

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

      document.getElementById('coords').value = results[0].geometry.location;
      // Let's say the location is NYC (40.7143528, -74.0059731)

     alert(document.getElementById('coords').value); //returns the correct value
     // however, this pops up after the pop up in function foo() 

   });
}

with the following HTML

<input type="hidden" id="coords" name="coords"/>

The real code is using Google Maps API if that makes a difference:


Solution

  • bar runs asynchronously because geocoder does. That means that

    document.getElementById('coords').value = results[0].geometry.location;
    

    actually executes after

    var myVar = document.getElementById('coords').value;
    

    You can't use ajax this way. All of your work that relies on results/status has to be done in the callback.