在Geocoder中返回未定义的函数

Function returning undefined in Geocoder

本文关键字:函数 未定义 返回 Geocoder      更新时间:2023-09-26

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

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

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