Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to add value to the correct object in a callback function?
    primarykey
    data
    text
    <p>The code below overwrites the var store every time the while loop runs. So when the callback runs the store value is usually the last item in the store array.</p> <pre><code>var stores = []; stores.push({'address': "1 California Ave, San Francisco, CA"}); stores.push({'address': "16 California Ave, San Francisco, CA"}); stores.push({'address': "20 California Ave, San Francisco, CA"}); stores.push({'address': "30 California Ave, San Francisco, CA"}); var geocoder = new google.maps.Geocoder(); var i = 0; while( i &lt; stores.length){ var store = stores[i]; geocoder.geocode({'address':store.fullAddress}, function(data, status){ store.latlng = data[0].geometry.location; } }); i++; }; </code></pre> <p>How do I add the correct latlng to the correct store?</p> <p>This doesn't work either because the var i is changed as well.</p> <pre><code>var i = 0; var storesObject = {} while( i &lt; stores.length){ var store = stores[i]; storesObject[i] = stores[i]; geocoder.geocode({'address':store.fullAddress}, function(data, status){ storesObject[i].latlng = data[0].geometry.location; } }); i++; }; </code></pre> <p>If I do this how do I match the results to the stores array?</p> <pre><code>var i = 0; var results = []; while( i &lt; stores.length){ var store = stores[i]; geocoder.geocode({'address':store.fullAddress}, function(data, status){ results.push(data[0].geometry.location); } }); i++; }; </code></pre> <p>UPDATE adding in a functional scope fixed my issue:</p> <pre><code>var i = 0; while( i &lt; stores.length){ (function(){ var store = stores[i]; geocoder.geocode({'address':store.fullAddress}, function(data, status){ store.latlng = data[0].geometry.location; } }); })(); i++; }; </code></pre> <p>see: <a href="https://stackoverflow.com/questions/10555097/gmaps-js-geocode-using-passing-variables-with-asynchronous-geocode-function?rq=1">GMaps JS Geocode: Using/Passing Variables With Asynchronous Geocode Function?</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload