Google Maps API函数没有及时返回结果

Google Maps API function does not return results in time

本文关键字:返回 结果 Maps API 函数 Google      更新时间:2023-09-26

所以我有一个具有以下属性的对象数组:Address, Latitude, LongitudeTitle

 poi("139 Main St", 0, 0, "Farmer's Market" ),
 poi("18 N Hopkins Ave", 37.4455, -143.7728, "YMCA" ),
 poi("42 Universe St", 37.4855, -143.8781, "Original Pizza #32" )

现在,第一个对象没有为纬度和经度设置任何内容,因此我希望使用Google的Geocode API来填充缺失的数据。我包含了API脚本链接与我的API密钥,这是正常工作。

然后我创建了一个for循环,它遍历数组并找到任何缺少数据的对象。它应该遍历并用正确的信息替换任何空单元格。然而,尽管信息被检索了,但它是在循环完成后才被检索的。我可以输出正确的信息,但只有在函数返回空数据之后。

for (i=0; i < poiArray.length; i++ ) {
    var curr = poiArray[i];
    if ( !curr.lat || !curr.long ) {
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': curr.address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                cur.lat = results[0].geometry.location.k;
                cur.long = results[0].geometry.location.B;
            } else {
                console.log('failed to include ' + curr.title);
                poiArray.splice(i--, 1);    
            }
       });  
    }
}

我试过timeout和嵌套函数,但似乎没有工作。有什么建议吗?


让我提一点更奇怪的:如果我在if (status == google.maps.GeocoderStatus.OK) {之后控制台变量i在我的for循环中,我得到我的数组的最后一个数字…每一次。并且循环似乎只更新数组中的最后一项,如果我在加载了来自Google的异步数据后控制我的poiArray

你可以用函数闭包来解决这个问题。此外,您不应该使用Google Maps Javascript API v3的未记录属性。k, . b),它们会随着API的更新而改变,从而破坏你的代码。

var geocoder = new google.maps.Geocoder();
function geocodeAddress(curr, i) {
  geocoder.geocode( { 'address': curr.address }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
       cur.lat = results[0].geometry.location.lat();
       cur.long = results[0].geometry.location.lng();
    } else {
       console.log('failed to include ' + curr.title);
       poiArray.splice(i--, 1);    
    }
  });  
}
for (i=0; i < poiArray.length; i++ ) {
    var curr = poiArray[i];
    if ( !curr.lat || !curr.long ) {
        geocodeAddress(curr, i);
    }
}