将地理编码器的位置保存到数组中
Save the location of geocoder into array
我有一个地址数组(选项卡),我想将所有地址的位置保存到另一个多维(测试)中,我已经尝试过这段代码,但它不起作用
var test = [];
for (var i = tab.length - 1; i >= 0; i--) {
var r=[];
geocoder.geocode({address: tab[i].toString()},function (result,status){
if (status == google.maps.GeocoderStatus.OK) {
r.push(result[0].geometry.location.k);
r.push(result[0].geometry.location.D);
}else{
r.push(0);
r.push(0);
};
})
test.push(r);
}
您必须在
地理编码回调中创建/推送临时数组r
:
var tab =['berlin','paris','rome'],
test =[],
geocoder=new google.maps.Geocoder();
for (var i = tab.length - 1; i >= 0; i--) {
geocoder.geocode({address: tab[i].toString()},function (result,status){
var r=[];
if (status == google.maps.GeocoderStatus.OK) {
r.push(result[0].geometry.location.lat());
r.push(result[0].geometry.location.lng());
}else{
r.push(0);
r.push(0);
};
test.push(r);
//print resulting array
if(test.length===tab.length){
document.body.textContent='['n ['+test.join('],'n [').toString()+']'n]';
}
})
}
body{white-space:pre;font-family:monospace;}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
另请注意:要访问 LatLng 的lat
和lng
,请使用具有相似名称的内置方法。属性k
和D
在 API 版本中不稳定。
但是数组方法存在一个问题:不能保证结果按所需顺序到达,您将无法获得地址和返回位置之间的关系。
另一种方法,它使用对象(使用地址作为键):
var tab ={'berlin':null,'paris':null,'rome':null},
geocoder=new google.maps.Geocoder();
for (var k in tab) {
geocoder.geocode(
{
address: k.toString()
},
(function(address){
return function(result,status){
if (status == google.maps.GeocoderStatus.OK) {
tab[address]={
lat:result[0].geometry.location.lat(),
lng:result[0].geometry.location.lng()
}
}
document.body.textContent=JSON.stringify(tab);
}
}(k)));
}
body{white-space:pre;font-family:monospace;}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
相关文章:
- 保存数组javascript
- 保存表中的行's在数组中的tbody,稍后使用它们
- 保存id数组's而不是对象
- JavaScript-保存、存储和更新数组
- Javascript-将类型化数组保存为blob,并作为二进制数据读回
- 使用javascript/jquery从现有数组中创建一个新数组,该数组保存项目存在的次数
- AJAX将JSON数组保存到多个JS变量中
- 我的函数不会返回要保存在数组中的对象
- Javascript数组只保存最近的对象
- 将对象属性保存到数组时出现奇怪的重复
- 将地理编码器的位置保存到数组中
- 如何在排序前保存数组的副本
- 如何使用保存数组名称的变量将对象文本添加到数组
- 使用猫鼬保存数组数据的更干净的代码
- Javascript:保存数组中重复项的索引
- 在重新加载时保存数组值并将其取回
- 如何在parse.com+AngularJS中使用for循环保存数组中的每个对象
- 使用postgresql保存数组进行Sequelize
- 对象,用于保存数组JQuery
- 如何在文件上快速保存数组