use*_*219 13 javascript asynchronous callback google-maps-api-3 geocode
我有一个表格要求提供一个位置列表(不是很多,通常只有3或4但这个数字是动态的).提交表单时,我必须解析数据,使用Google地理编码获取位置,然后绘制一条连接点的行.我解析工作,但我坚持使用地理编码部分,主要是因为它的异步性质.假设我的地址字符串存储在数组'addresses'中,这是我得到的:
function someFunction(addresses) {
var coords = [];
for(var i = 0; i < addresses.length; i++) {
currAddress = addresses[i];
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address':currAddress}, function (results, status)
if (status == google.maps.GeocoderStatus.OK) {
coords.push(results[0].geometry.location);
}
else {
throw('No results found: ' + status);
}
});
}
}
// Initially I tried to work with the data here, but it wasn't all present yet.
}
Run Code Online (Sandbox Code Playgroud)
绘制线条很容易,我已经在用户提供地理纬度/经度坐标之前完成了这项工作.我的问题是,因为坐标只是在回调中添加,我怎么知道它什么时候完成?我不能将它转储到函数中并放入回调因为我需要等到所有坐标都被处理完毕.
我还读到了一些有问题的人没有按顺序返回,但我不理解提供的回复.如果某人有答案可以帮助我解决我的具体问题,并确保结果恢复正常,我将不胜感激.
注意:我手动轰炸了那段代码,所以可能会出现错别字.到目前为止,我的实际代码"有效",我只是不知道在处理完所有地址后,我将从做什么转移到做什么.此外,目前正在开发这种测试的内部应用程序.测试完成后,它将完全符合Google的服务条款.这意味着我没有可以链接到的页面.整个应用程序还有超过2,000行代码,并且此时包含一些专有的公司信息,最终将逐步淘汰,因此粘贴整个内容或将其发送出去是不可行的.我希望这不会构成太大的问题.
Ins*_*dJW 14
function someFunction(addresses, callback) {
var coords = [];
for(var i = 0; i < addresses.length; i++) {
currAddress = addresses[i];
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address':currAddress}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
coords.push(results[0].geometry.location);
if(coords.length == addresses.length) {
if( typeof callback == 'function' ) {
callback();
}
}
}
else {
throw('No results found: ' + status);
}
});
}
}
}
}
//Usage
someFunction(addresses, function() {
// Do something after getting done with Geocoding of multiple addresses
});
Run Code Online (Sandbox Code Playgroud)
使用回调功能是惊人的
您可以通过将结果数量与地址数量进行比较来检查是否所有呼叫都已完成:
function someFunction(addresses) {
var currAddress, coords = [];
for (var i = 0; i < addresses.length; i++) {
currAddress = addresses[i];
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'address':currAddress}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
coords.push(results[0].geometry.location);
// Check if all calls have been processed
if (coords.length == addresses.length) {
someOtherFunction(coords);
}
}
...
});
}
}
}
function someOtherFunction(coords) {
// Geocoding has been done for all addresses
...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15274 次 |
最近记录: |