地理位置问题 - 绝对的初学者

时间:2012-10-19 11:28:35

标签: javascript geolocation

我正在浏览StackOverflow并查看所有网络资源,但没有人告诉我如何完成这项工作。

我只想获取用户当前位置的纬度数。我想通过触发一个方法来做到这一点:getLat()就是这样。

它无效。我尝试返回,它一直未定义。我尝试更改变量,但也失败了。各地的论坛都说你需要聪明一点,因为它是“异步的”而且API阻止你像这样得到getLat(),但是应该有办法。我不明白这是什么意思,我很乐意就此得到一些建议。

function getLat(){
var lat1;
function getLocation() {
    navigator.geolocation.getCurrentPosition (function (position){
        var coords = position.coords.latitude;
        lat1 = coords; 
    })
}
return lat1;
}

function getLong(){
var lng1;
function getLocation() {
    navigator.geolocation.getCurrentPosition (function (position){
        var coords = position.coords.longitude;
        lat1 = coords; 
    })
}
return lng1;
}

1 个答案:

答案 0 :(得分:0)

getLocation函数未被调用。因此,lat1lng1虽然已声明,但仍然没有值undefined

此外,getCurrentPosition是异步的。从技术上讲,你不会返回数据,当数据处理完毕时,你会传递一个函数,一个" todo&#34 ;.

请改为尝试:

//define a function receiving a callback
function getLat(callback){

    //fire the getCurrentposition function
    navigator.geolocation.getCurrentPosition(function(position){

        //fire the callback that was passed, 
        //passing to it the latitude
        callback.call(this,position.coords.latitude);
    });
}

//now we use the function
getLat(function(lat){
    //do everything else via the lat variable here!
});

//now do the same for getLng