javascript - 当前坐标返回未定义

标签 javascript

这个问题在这里已经有了答案:





Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

(6 个回答)


7年前关闭。




我正在尝试使用 getLocation 函数来获取当前位置坐标并在将来使用这些坐标进行距离计算。运行以下代码后,我得到了未定义。

<script type="text/javascript">
var currentLatitude;
var currentLongitude;

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getCoordinates);
    } else { 
        document.getElementById("asdfsdafsdaf").innerHTML = "Geolocation is not supported by this browser.";
    }
}

function getCoordinates(position) {
    currentLatitude = position.coords.latitude;
    currentLongitude = position.coords.longitude;   
}

var xhr = new XMLHttpRequest();
xhr.open("POST", "rsvpButton.php", true);
var formData = new FormData();
    formData.append("userID", 100100);
xhr.send(formData);

xhr.onload=function(){
    getLocation();
    alert("1"+currentLongitude+" and "+currentLatitude);
    //some other codes to display the page
    //...
}
</script>

我以为我把这 2 个变量放在了错误的地方,但经过多次尝试后仍然无法正常工作。请问有什么帮助吗?提前致谢。

更新:我尝试将底部代码放入回调函数中,但整个页面消失了。

最佳答案

getCurrentPosition接受回调,因为它是异步的。在此处阅读更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation.getCurrentPosition

试着把 alert在回调中:

<script type="text/javascript">
var currentLatitude;
var currentLongitude;

function getLocation(callback) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(callback);
    } else { 
        document.getElementById("asdfsdafsdaf").innerHTML = "Geolocation is not supported by this browser.";
    }
}

var xhr = new XMLHttpRequest();
xhr.open("POST", "rsvpButton.php", true);
var formData = new FormData();
    formData.append("userID", 100100);
xhr.send(formData);

xhr.onload=function(){
    getLocation(function (position) {
        var currentLatitude = position.coords.latitude;
        var currentLongitude = position.coords.longitude;   

        alert("1"+currentLongitude+" and "+currentLatitude);
        //some other codes to display the page
        //...
    });

}
</script>

关于javascript - 当前坐标返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26535019/

相关文章:

javascript - 一页滚动插件 : I don't want the whole page to slide

javascript - 在 Bootstrap 模式顶部显示 "busy wait"

javascript - 如何使用 JavaScript/jQuery 更改内容?

javascript - 将函数序列化和反序列化到 JSON 或从 JSON 反序列化

javascript - 是否有等效的方法来设置模拟实现,而不是使用 jest 的 __mocks__ 目录方法?

javascript - 类型错误 : getState is not a function when adding middleware to Redux

javascript - 包括 ActionController::Live 会中断现有的 AJAX 调用

javascript - 如果 id 消失,提交按钮可以工作

javascript - Angular typescript : Swagger CodeGen Generator making all class properties Nullable

javascript - IE 刷新页面出现几秒大字,如何解决?