2014-08-31 40 views
0

有人可以看看我的代碼並告訴我我做錯了什麼嗎?我知道Googlemaps geocoder是一個異步函數,所以需要回調來處理結果。所以我在這裏下面的例子,但我仍然不能得到它的工作:無法讓Googlemaps Geocoder通過回調返回LatLng

How do I return a variable from Google Maps JavaScript geocoder callback?

我想給我的codeAddress功能的實際地址和一個回調函數。如果results數組有我發送lat和lng到回調函數。

codeAddress = function(address, callback) { 
    var gpsPosition = {}; 
    if (geocoder) { 
     geocoder.geocode({'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      if (results[0]) { 
      console.log("got results!"); 
      var lat = results[0].geometry.location['B']; 
      var lng = results[0].geometry.location['k']; 
      callback(lat, lng); 
      } else { 
      alert("No results found"); 
      } 
     } else { 
      alert("Geocoder failed due to: " + status); 
     } 
     }); 
    } 
    }; 

這是回調函數。基本上它需要codeAddress函數的lat和lng,並將lat和lng放入一個散列並將其返回。這個想法是,當我創建一個新的地圖標記時,將散列存儲到一個名爲location的變量和參考location

createGPSPosition = function(lat, lng){ 
    console.log("createGPSPosition called with lat and lng:"); 
    console.log(lat); 
    console.log(lng); 
    var gpsPosition = {}; 
    gpsPosition.B = lat; 
    gpsPosition.k = lng; 
    console.log("gpsPosition:"); 
    console.log(gpsPosition); 
    return gpsPosition; 
    }; 

當我運行此代碼console.log(gpsPosition);實際上記錄了最終的哈希對象。但我仍然沒有看到被退回的對象......所以當我這樣做:

var stuff = codeAddress("1600 Amphitheatre Pkwy, Mountain View, CA 94043", createGPSPosition) 

stuff仍然輪番上漲爲undefined。這裏發生了什麼?

+0

可能的重複[爲什麼我的變量在函數內部修改後沒有改變? - 異步代碼引用](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – geocodezip 2014-08-31 13:18:48

回答

0

此問題是您期望asynchronous代碼以同步方式工作。在codeAddress完成搜索之前定義了stuff。最簡單的解決方案是提供不同的回調,在其中定義stuff並在那裏使用它。這應該工作得很好:

codeAddress("1600 Amphitheatre Pkwy, Mountain View, CA 94043", function(lat, lng){ 
    var stuff = createGPSPosition(lat, lng); 
    console.log(stuff); // => your gpsPosition object 
}); 

另一種方法是學習Promises