2012-10-25 37 views
1

好吧,我已經搜索了一段時間解決這個問題,但我沒有發現任何具體的問題。 在您將我的服務條款告訴我之前,請先閱讀問題的結尾!將地理編碼結果保存到數組 - 關閉問題

所以這裏的想法: 我想要使用Google的地理編碼器將地址的緯度和經度保存到一個數組中。我設法正確計算了所有的值,但我似乎無法將其保存到數組中。我已經使用匿名函數將地址傳遞給該函數,但保存仍然不起作用。請幫忙!

關於Google的服務條款:我知道我可能不會將此代碼保存到任何地方,也不會將其顯示在Google地圖中。但是我需要將其另存爲一個kml文件,以便稍後將其提供給Google地圖。我知道,創建地圖會更方便,但是由於其他原因,這是不可能的。

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

回答

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

}

+0

我已經試過了,但它不工作。你的代碼,即使與匿名函數一起使用時,也只會保存adressdaten [adressdaten.length] [6]中計算出的最後一個座標,所以在一個甚至不應該被觸摸的字段中。我明白,這是因爲關閉,這正是我需要解決的問題。 –

+0

你沒有那麼說。如果這是問題,那麼使用函數閉包將返回的地址與數組中的索引相關聯,並更新答案。 – geocodezip

+0

好的,謝謝。抱歉沒有清楚地提出問題。 我終於意識到我犯的錯誤。我試圖將geocodeAddress()作爲一個獨立的函數來實現,不包括在下面代碼的範圍內。現在一切正常! –