函数在Geocoder中返回undefined

我正在使用Google maps v3地理编码器对地址进行地理编码,然后使用getJSON将jQuery文件中的2个坐标点传递给PHP文件。

问题:但是,我注意到执行地理编码function的函数不断返回未定义的值! 因此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(''); . . . 

Geocoder JSfunction

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

您无法通过回调将该函数的值返回给Google代码。 这没有道理; “geocode()”函数是异步的 。 外部函数将在回调运行时返回。

正确的方法是模仿Google 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(''); // ... }); }); 

它就像您的原始代码,但不是将地理编码结果返回给您的代码,而是将其作为参数传递给您提供的回调函数。