gpt4 book ai didi

JavaScript 异步作用域

转载 作者:行者123 更新时间:2023-11-28 20:20:30 24 4
gpt4 key购买 nike

我开始学习 javascript,并且正在摆弄 GPS。目前,我在确定函数范围时遇到问题。

代码

$(document).ready(function () {
var lat, lng;

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
$(document).data('lat', position.coords.latitude); //undefined outside
lat = position.coords.latitude; //undefined outside
lng = position.coords.longitude; //undefined outside
});
}

var coords = new google.maps.LatLng(lat,lng); //lat & lng are undefined
});

问题在于,我在 getCurrentPosition 调用的函数的本地范围内分配的任何值都不会保留。处理此问题的最佳实践是什么。我假设它只是返回一个包含数据的对象,但我到底该怎么做呢?我尝试这样做,但仍然不起作用

最佳答案

嗯,多亏了上面的两条评论,我明白了。问题不是范围问题,而是异步问题。引用stackoverflow.com/q/14220321/218196

$(document).ready(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, { maximumAge: 75000 });
}

function success(position) {
var coords = new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude);
initMap(coords);
}

function error(err) {
//coordinates of LA
initMap(new google.maps.LatLng(34,118));
}


function initMap(coords) {
//logic here
}
});

关于JavaScript 异步作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18432768/

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