我正在使用 Google map v3 地理编码器对地址进行地理编码,然后使用 getJSON
将 2 个坐标点从 jQuery 文件传递到 PHP 文件。
问题:但是,我注意到执行地理编码功能的函数不断返回未定义的值!因此 PHP 文件接收到一个 undefined variable 。我哪里出错了?
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);
}
});
}
最佳答案
您不能通过对 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('');
// ...
});
});
这就像您的原始代码,但不是将地理编码结果返回到您的代码,而是作为参数传递给您提供的回调函数。
关于javascript - Geocoder 中返回未定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7967397/