出于某种原因,我在运行和编辑代码时不断遇到这两个错误。
请注意,我使用全局变量myArr。我一直在说:
"错误
myArr[j]
未定义"
每当我尝试解析函数内的数据时,选择事实"或者从myArr
返回parseJSONdata()
,而不是:
"错误XHLHttpRequest未定义"。
var myArr= [];
function parseJSONdata() {
//parse data
var xmlhttp = new XMLHttpReqsuest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myArr = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", "Fact.json", true);
xmlhttp.send();
}
function ChooseFact() {
// compare
for (let i = 0; i <bul.length; i++){
if (i == key){
var j = i;
}
}
return myArr[j].Fact;
}
这是我关注的代码部分。
以下是整个代码供参考。
var bul = [ {
"Building" : "CEER",
"Latitude" : 40.0366404,
"Longitude" : -75.3457346
}, {
"Building" : "Bartley",
"Latitude" : 40.034595,
"Longitude" : -75.3383853
}, {
"Building" : "Mendel",
"Latitude" : 40.0378151,
"Longitude" : -75.3419795
}, {
"Building" : "Falvey",
"Latitude" : 40.037469,
"Longitude" : -75.342546
} ];
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var w =NearestBuilding(latitude,longitude);
x.innerHTML = w;
x.innerHTML = ChooseFact();
}
function Deg2Rad(deg) {
return deg * Math.PI / 180;
}
function convertDistance(lat1, lon1, lat2, lon2) {
lat1 = Deg2Rad(lat1);
lat2 = Deg2Rad(lat2);
lon1 = Deg2Rad(lon1);
lon2 = Deg2Rad(lon2);
var R = 6371e3; // km
var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
var y = (lat2 - lat1);
var d = Math.sqrt(x * x + y * y) * R;
return d;
}
var key;
function NearestBuilding(latitude, longitude) {
var mindif = 999999;
var closest;
for (let i = 0; i < bul.length; i++) {
var dif = convertDistance(latitude, longitude, bul[i].Latitude,
bul[i].Longitude);
console.log(i,dif);
if (dif < mindif) {
closest = i;
mindif = dif;
}
}
// if (dif<5){
key = closest;
return bul[closest].Building;
// }
// else{
// return "Error: Must be less than 15 feet away from a Building";
// }
}
var myArr = [];
function parseJSONdata() {
//parse data
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myArr = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", "Fact.json", true);
xmlhttp.send();
return myArr;
}
function ChooseFact(){
// compare
for (let i = 0; i <bul.length; i++){
if (i == key){
var j = i;}
}
myArr= parseJSONdata();
return myArr[j].Fact;
}