2015-06-28 49 views
0

一個簡單的,我似乎無法正常工作。GoogleMaps API地理編碼回調

我有以下幾點:

function geocode(address, callback) { 
    if (typeof (geocoder) == 'undefined') geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': address }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      callback({ Latitude: results[0].geometry.location.lat(), Longitude: results[0].geometry.location.lng() }); 
     } 
     else { 
      callback(0); 
      console.log("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
} 

那得到由名爲:

  var latitude = ''; 
      var longitude = ''; 
      geocode(self.address(), function (result) { 
       if (result === 0) { 
        //Error with geocoding 
       } 
       else { 
        latitude = result.Latitude; 
        longitude = result.Longitude; 
       } 
      }); 
//Do some stuff with latitude and longitude 

現在,這樣做的結果返回,但他們這樣做異步這是我認爲回調將克服例如latitudelongitude值未定義。

回答

0

我覺得這個我正確的方式

var latitude = ''; 
var longitude = ''; 
geocode(self.address(), function (result) { 
    if (result === 0) { 
     //Error with geocoding 
    } 
    else { 
     .... 
     manage your latitude, longitude 

     .... 
    } 
}); 


function geocode(address) { 
    if (typeof (geocoder) == 'undefined') geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': address }, function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      latitude = results[0].geometry.location.lat(); 
      longitude =results[0].geometry.location.lng() }); 
     } 
     else { 

      console.log("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
+0

感謝您的反饋,很遺憾你的建議不工作,實際上,我不知道如何可以工作,因爲你不直接處理此作爲回調爲此它會是異步的。也許我不清楚,經度和緯度值的「工作」只是這些值不能「及時」填充(因爲對gecode的調用是異步的)。 – user1470994