为什么这个函数总是返回'undefined'

时间:2009-05-28 10:36:19

标签: javascript google-maps

function getLongLat(address)
{
geocoder = new GClientGeocoder();
if (geocoder) {
       geocoder.getLatLng(address,
         function(point) {
           if (!point) {
             return "null";
           } else {          
         return point;
           }
         }
       );
     }
}   

如果我提醒(点)我得到经度和纬度。

4 个答案:

答案 0 :(得分:4)

试试这个:D

function getLongLat(address)
{
        geocoder = new GClientGeocoder();
        if (geocoder) {
           return geocoder.getLatLng(address,
             function(point) {
               if (!point) {
                return "null";
               } else {          
                    return point;
               }
             }
           );
        }
        return false;
 }

答案 1 :(得分:3)

这是因为你的函数没有return语句。

作为geocoder.getLatLng的参数调用的内部函数确实有一个return语句,这让你感到困惑。我建议你提取内部函数来减少令人困惑的方面。

试试这个:

function convert_to_null_if_falsy(value) {
    return value || "null";
}    

function getLongLat(address) {
    geocoder = new GClientGeocoder();
    return geocoder.getLatLng(address, convert_to_null_if_falsy);
}

我不确定你为什么要在回调函数中返回字符串"null"而不是undefined,但是这段代码的功能相同而且麻烦要少得多。

答案 2 :(得分:1)

如果geocoder不是 true 怎么办?并且geocoder.getLatLng也没有返回任何值。

因此,让两者都返回一些东西,或许:

function getLongLat(address) {
    geocoder = new GClientGeocoder();
    if (geocoder) {
        return geocoder.getLatLng(address, function(point) {
            if (!point) {
                return "null";
            } else {
                return point;
            }
        });
    }
    return "null";
}

答案 3 :(得分:1)

请记住,getLatLng()是异步的:你传入一个匿名函数,让它在完成时执行。

你的getLongLat()函数在这种情况下将无法返回点,因为匿名函数是在一个完全不同的上下文中异步运行的:你的函数将在Google的意愿之前执行并返回,而且甚至不会在外部职能的范围。

你需要在匿名函数中调用你想要操作的任何代码:

function getLongLat(address)
{
    geocoder = new GClientGeocoder();
    if (geocoder) {
       return geocoder.getLatLng(address,
         function(point) {
           // point is only in scope for this anonymous inner function
           // which is called when your request to Google's service completes
           if (!point) {
              // your error condition if a point isn't found
              // omgMissingPoint(point);
           } else {          
              // your function to process points here.
              // processPoint(point);
           }
         }
       );
    }

}

相关问题