我目前正在使用Google地图的地理编码,并需要创建包含多个数组的数组。
基本上,我需要创建这样一个数组:
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]
];
但是需要动态操作!我需要这个数组来在地图上标记位置。
我的操作:
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);
问题,疑问:
我没有看到任何错误,但最终locations[]数组为空。
如果需要,这里是控制台屏幕截图:
geocode
是异步的。在处理数组之前,您需要等待所有调用都有响应。 - PrinzhornmyArray.push(new Array())
。myArray
必须至少被实例化为一个空数组,例如myArray = []
。 - Chris Halcrow