gpt4 book ai didi

javascript - 当前坐标返回未定义

转载 作者:行者123 更新时间:2023-12-03 18:08:51 26 4
gpt4 key购买 nike

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





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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com