Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>i didn't have time to test the code, but it should work this way:</p> <pre><code> function requestLocations( addresses, callback ) { var remainingLocations = addresses.length; var locations = []; for (var i = 0; i &lt; addresses.length; ++i){ var address=addresses[i]; // the address e.g. 15 Main St, Hyannis, MA locations[i] = []; geocoder.geocode({ 'address': address}, ( function(idx) { return function(result) { locations[idx] = [ addresses[idx], results[0].geometry.location.hb, results[0].geometry.location.ib, idx ]; //decrement the number of remaining addresses --remainingLocations; //if there are no more remaining addresses and a callback is provided then call this calback with the locations if( remainingLocations === 0 &amp;&amp; callback ) { callback(locations); } }; // returns the real callback function for your geocoding })(i) //direct invocation of function with paramter i for scoping ); } } requestLocations(addresses, function( locations ) { console.dir(locations); console.log(locations.length); }); </code></pre> <p>The Problem with your code is the following. First this part of the code is executed:</p> <pre><code> var locations = []; // The initial array for (var i = 0; i &lt; addresses.length; ++i) { var address = addresses[i]; // the address e.g. 15 Main St, Hyannis, MA geocoder.geocode({ 'address': address }, function(results) { //this part is called later when that data is ready (it is an asynchronous callback) }); }; //because of the async request this is still 0 console.log(locations.length); </code></pre> <p>After that the callbacks itself are called as soon as the browser receives the data from the server:</p> <pre><code> function(results) { var obj = { 0: address, 1: results[0].geometry.location.hb, 2: results[0].geometry.location.ib, 3: i }; console.log(obj); locations.push(new Array()); locations[i].push(obj); } </code></pre>
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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