2013-04-13 116 views
1

我有一個問題,如果我把Geoencoding的結果放入一個變量,變量返回空。這裏是我的代碼:谷歌地圖API v3,地理定位不正確返回

地圖初始化:

function init_map() { 
    geocoder = new google.maps.Geocoder(); 

    var center_address = get_long_lat("Salisbury, UK"); 
    var latlng = new google.maps.LatLng(center_address); 

    var mapOptions = { 
    zoom: 8, 
    center: latlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
    } 

    map = new google.maps.Map(document.getElementById("gmap"), mapOptions); 
} 

正如你可以看到,我試圖讓地圖的中心到我的家鄉通過使用自定義功能get_long_lat轉換地址,以龍和緯度:

長期做下去&緯度

function get_long_lat(address) { 

     var result = ""; 

     geocoder.geocode({ 'address': address, 'region': 'uk' }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       result = results[0].geometry.location; 
      } else { 
      result = "Unable to find address: " + status; 
      } 
     }); 

     return result; 
    } 

現在,結果返回爲空字符串。但是,如果我要顯示結果[0] .geometry.location的警報,它顯示正確的值,我期待?

爲什麼不想返回這個值?

+1

[Google maps API問題與地理編碼器]的可能重複(http://stackoverflow.com/questions/15606660/google-maps-api-issue-with-geocoder) – geocodezip

回答

0
geocoder.geocode({ 'address': address, 'region': 'uk' }, function(results, status) {}); 

這段代碼會調用Google服務器來檢索地理編碼信息。它收到來自Google服務器的響應後,會執行指定的回調函數。

return result; 

該行在回調函數檢索到信息之前被命中,因此結果仍爲空。當信息被檢索時,回調函數被調用並且結果被填充。但是太遲了,「get_long_lat」函數已經返回了結果,在返回時它仍然是空的。

問題是,返回結果的回調函數是異步運行的。

,如果你寫這樣它的工作:

function init_map() { 
    geocoder = new google.maps.Geocoder(); 

    geocoder.geocode({ 'address': 'Salisbury, UK', 'region': 'uk' }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 

     var mapOptions = { 
      zoom: 8, 
      center: results[0].geometry.location, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     } 

     map = new google.maps.Map(document.getElementById("gmap"), mapOptions); 

     } else { 
     //Do whatever you want to do when the address isn't found. 
     //result = "Unable to find address: " + status; 
     } 
    }); 

} 

現在後的谷歌服務器已經返回他們的反應在MapOptions對象僅被初始化。

2

地理編碼器是異步的。您不能返回異步函數的結果。您應該使用回調內的result值。

更具體地說,發生了什麼事是你的return result;行在result變量被分配之前實際上正在執行。

+0

對不起,即時通訊一個完整的JS noob,什麼做你的意思是使用回調中的結果值?你有一個我可以查看的小代碼示例> – ChrisBratherton

+0

你傳遞給geocoder的匿名函數,接受參數'results'和'status'的函數?這是一個回調函數。對該回調函數內的'result'值做任何你想做的事情。 – 2013-04-13 22:06:30