javascript - 将地理编码器结果保存到数组 - 关闭问题

标签 javascript google-maps-api-3 closures

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

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

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

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;
}

最佳答案

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

类似于(未测试)

更新为使用函数闭包

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); 

}

关于javascript - 将地理编码器结果保存到数组 - 关闭问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13067403/

相关文章:

javascript - 使用ajax动态加载谷歌地图v3

php - 作为类(class)成员关闭?

closures - 从函数返回一个闭包

javascript - 如何触发使用闭包变量的事件?

javascript - NodeJS : Not able to access an image using ajax GET method. 但相同的 URL 在浏览器中加载图像没有任何问题

javascript - "useEffect has a missing dependency"警告有时是错误的吗?

javascript - 将 async/await 阻塞一个线程 node.js

javascript - PURE Javascript 是同步还是异步?

xml - 从 xml 文件在 google maps API V3 中添加标记

php - 从已知位置查找最近的列出(数组?)城市