我遇到以下脚本的问题:
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
// Start of geolocation block
function theCallback(position) {
//console.log(position.coords);
crd = position.coords;
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}
else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocation(callback)
{
if(navigator.geolocation) {
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
navigator.geolocation.watchPosition(theCallback, errorHandler, options);
}
else {
alert('W3C Geolocation API is not available');
}
}
// End of geolocation block
function weatherReq(crd) {
var location = "lat=" + lat + "&" + "lon=" + lon;
var appId = "---THEAPIKEY---"
var request = "http://api.openweathermap.org/data/2.5/weather?" + location + "&APPID=" + appId;
var weatherReq = new XMLHttpRequest();
weatherReq.open("GET", request, false);
console.log(request);
weatherReq.send();
if (weatherReq.status === 200) {
respJSON = JSON.parse(weatherReq.responseText);
return 0;
}
else {
alert("Some error occurred during the request");
return 2;
}
}
function main () {
getLocation(function(data) {
lat = data.latitude;
lon = data.longitude;
lat -= (lat % 1);
lon -= (lon % 1);
console.log(crd + " " + lat + " " + lon);
weatherReq(lat, lon);
console.log(respJSON.id);
});
var randomColor = getRandomColor();
$("body").css("transition", "background-color 1s ease");
$("body").css("background-color", randomColor);
}
$(document).ready(main);
它不起作用。参数&#34;数据&#34; (第61行)没有得到一个值,也没有变量&#34; crd&#34; (第14行)。
我不明白问题是由于地理位置的异步性还是由变量范围引起的。
顺便说一下,如果我尝试在main中声明变量,控制台会告诉它未定义。
提前致谢。