I'm currently working with Google maps' geocoding and need to create an array that will contain arrays as an elements.
Basically i need to create this:
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
But dynamically! I need this array to put pins on a map later.
What I'm doing:
var locations = []; // The initial array
for (var i = 0; i < addresses.length; ++i){
var address=addresses[i]; // the address e.g. 15 Main St, Hyannis, MA
geocoder.geocode({ 'address': address}, 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);
});
};
console.log(locations.length);
The problem, question:
I don't see any errors but at the end locations[] array is empty.
Here is a console screen if needed:
This should be all you need:
geocoder.geocode({ 'address': address}, function(results){
locations.push([
address,
results[0].geometry.location.hb,
results[0].geometry.location.ib,
i //this is actually going to always be
//addresses.length because the callback won't fire
//until well after the loop has completed.
//Is this really a necessary field to have
//in your array? if so, you'll need to refactor a bit
]);
});