【问题标题】:Saving geocoder results to an array - Closure Trouble将地理编码器结果保存到数组 - 关闭问题
【发布时间】:2012-10-25 11:17:11
【问题描述】:

好的,所以我已经搜索了一段时间以寻找解决此问题的方法,但我没有找到任何具体的解决方案。 在您向我指出 Google 的服务条款之前,请阅读到问题的结尾!

所以这是一个想法: 我想使用 Google 的地理编码器将地址的纬度和经度保存到数组中。我设法正确计算了所有值,但似乎无法将其保存到数组中。我已经使用匿名函数将地址传递给函数,但保存仍然不起作用。请帮忙!

关于 Google 的服务条款:我知道我可能不会将此代码保存在任何地方,也不会将其显示在 Google 地图中。但我需要将其保存为 kml 文件,以便稍后输入谷歌地图。我知道,只创建地图会更方便,但由于其他原因,这是不可能的。

adressdaten[] 是一个包含地址数据的二维数组 这是代码:

for (i=1; i<adressdaten.length-1; i++)  {
//Save array-data in String to pass to the Geocoder
var adresse = adressdaten[i][3] + " " + adressdaten[i][4];
var coordinates;
var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': adresse}, (function (coordinates, adresse) {
        return function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
               var latLong = results[0].geometry.location;
               coordinates = latLong.lat() + "," + latLong.lng();


        } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        }
    })(coordinates, adresse));
    adressdaten[i][6] = coordinates;
}

【问题讨论】:

    标签: javascript google-maps-api-3 closures


    【解决方案1】:

    这是一个常见问题解答。地理编码是异步的。您需要将结果保存在从服务器返回时运行的回调函数中。

    类似的东西(未测试)

    更新为使用函数闭包

    function geocodeAddress(address, i) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
           var latLong = results[0].geometry.location;
           coordinates = latLong.lat() + "," + latLong.lng();
           adressdaten[i][6] = coordinates;
        } else {
           alert('Geocode of '+address+' was not successful for the following reason: ' + status);
        }
      });
    }
    
    var geocoder = new google.maps.Geocoder();
    for (i=1; i<adressdaten.length-1; i++)  {
      //Save array-data in String to pass to the Geocoder
      var adresse = adressdaten[i][3] + " " + adressdaten[i][4];
      var coordinates;
      geocodeAddress(addresse, i); 
    

    }

    【讨论】:

    • 我试过了,但它不起作用。您的代码,即使与匿名函数一起使用,也只会保存在 adressdaten[adressdaten.length][6] 中计算的最后一个坐标,因此在一个甚至不应该被触及的字段中。我知道这样做是因为关闭,而这正是我需要解决的问题。
    • 你没有这么说。如果这是问题所在,则使用函数闭包将返回的地址与数组中的索引相关联,更新答案。
    • 好的,谢谢。很抱歉没有清楚地提出问题。我终于意识到我犯的错误。我尝试将 geocodeAddress() 实现为一个单独的函数,不包括在下面的代码范围内。现在一切正常!
    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2013-06-14
    相关资源
    最近更新 更多