2011-11-01 44 views
2

我正在使用谷歌地圖v3 geocoder地址解析地址,然後通過2個座標點從jQuery文件到PHP文件使用getJSON函數返回undefined在地理編碼器

問題:但是,我注意到做地理編碼功能的函數一直返回一個未定義的值!因此PHP文件接收一個未定義的變量。我哪裏做錯了?

jQuery代碼

var search_latlng = geocodeAddress(search_location); 
console.log(search_latlng); 

$.getJSON('/main/get_places', {search_location: search_latlng}, function(json){ 
     $("#result_listing").html(''); 
. 
. 
. 

地理編碼器JS功能

function geocodeAddress(address) { 

    var latlng = new Array(2); 

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

回答

4

無法通過回調從函數返回一個值到谷歌代碼。這個不成立; 「地理編碼()」功能是異步。外部函數將在您的回調運行時返回。

正確的方法做,這是模仿谷歌API本身:給出函數的回調參數,然後在那裏執行你的「事後」的工作:

function geocodeAddress(address, callback) { 

    var latlng = new Array(2); 

    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      latlng[0] = results[0].geometry.location.lat(); 
      latlng[1] = results[0].geometry.location.lng(); 
      callback(latlng); // call the callback function here 
     } else { 
      console.log("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
} 

編輯 —作爲一個例子你會如何使用:

geocodeAddress(search_location, function(search_latlng) { 
    console.log(search_latlng); 
    $.getJSON('/main/get_places', {search_location: search_latlng}, function(json){ 
    $("#result_listing").html(''); 
    // ... 
    }); 
}); 

這就像你的原碼,但不是具有地址解析結果返回你的代碼,它作爲真實傳遞參數提供給您提供的回調函數。

+0

感謝您的回覆!所以'callback'是其他地方定義的一個普通函數,我將它傳遞給'geocoderAddress()'? 'callback()'函數可以使用'latlng'變量並將其返回給另一個變量'search_latlng'以傳遞給'getJSON'函數? – Nyxynyx

+0

本質上,您所做的與Google API處理核心異步事務(滿足地理編碼查詢的底層HTTP請求)完全相同。您將一個函數傳遞給Google API,因此* your * API將被寫入,以便在您從別處調用它時傳遞一個處理函數。 – Pointy

+0

嗨Pointy,我的javascript不是很好,所以我可以'理解你。你能在你發佈的代碼中編寫一個示例回調函數代碼嗎?我嘗試了谷歌搜索,但似乎不是我明白你告訴我的回調函數。 – Nyxynyx