2013-02-14 103 views
0

首先发布在这里!试图解决这一问题并寻找答案在线,但没有运气 - 我知道它在那里,但不能似乎算起来OUT-我有一个JavaScript代码返回用户的位置,如下所示:JS的返回值与其从外部返回的功能不一样

var myLatlon = navigator.geolocation.getCurrentPosition(onSuccess, onError); 

并且功能如下:

var onSuccess = function(position) { 
    var latlon=position.coords.latitude+','+position.coords.longitude; 
    return latlon; 
}; 

当我做一个console.log(latlon);在上面的函数内部,它返回由逗号分隔的实际纬度和经度。

但是当我在第一行之后执行console.log(myLatlon)时;它返回:{“timer”:true}

我需要从我的函数返回实际的经度和纬度。有任何想法吗?

回答

1

您不能从navigator.geolocation.getCurrentPosition返回值。这就是异步调用的本质。在调用回调之前,呼叫navigator.geolocation.getCurrentPosition完成。您必须在您的onSuccess回调中使用您的坐标

通常重构您的代码与返回它的效果几乎相同。

navigator.geolocation.getCurrentPosition(function(position){ 
    // Use position from here 
}, onError); 
// This line is reached before the commented line in the anonymous function above, that's why you can't return the value 
+0

完美,工作!谢谢! – galgo 2013-02-14 20:16:33

1

通常,您根本无法从用于处理异步执行的回调中返回。必须在回调中调用任何取决于(如)返回的值的代码。

这就是异步工作原理。