为什么我的变量在我的函数之外未定义?

时间:2017-07-29 10:11:19

标签: javascript html

我是javascript的新手,我正在尝试建立一个在用户区域显示温度的网站,但我的lalg变量在我的{{1}之外未定义函数,所以我无法成功调用API来获取天气。

这是完整的代码:

showPosition()

我决定使用var la; var lg; function getLocation() { if (navigator.geolocation) navigator.geolocation.getCurrentPosition(showPosition); } function showPosition(position) { la= position.coords.latitude; lg= position.coords.longitude; } getLocation(); var url="https://fcc-weather-api.glitch.me/api/current?lat=" + la + "&lon=" + lg; document.getElementById("im").innerHTML="Latitude:" + la; fetch(url) .then((resp) => resp.json()) .then(function(data) { document.getElementById("temper").innerHTML="Temperature:" + data.main.temp; }) .catch(function(error) { console.log("error: " + error); }); 行测试lalg变量是否正确,但我得到document.getElementById("im").innerHTML="Latitude:" + la。我在Latitude:undefined函数中进行了相同的测试,并且正确定义了变量。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

问题是showPosition没有立即被调用(例如,初始化GPS需要一些时间)。因此,在收到您的职位数据之前,您必须等待您的请求:

var la;
var lg;

function getLocation() {
 if (navigator.geolocation)
   navigator.geolocation.getCurrentPosition(showPosition); 
}

function showPosition(position) {
 la = position.coords.latitude;
 lg = position.coords.longitude;

 var url="https://fcc-weather-api.glitch.me/api/current?lat=" + la + "&lon=" + lg;
 document.getElementById("im").innerHTML="Latitude:" + la;

 fetch(url)
  .then((resp) => resp.json())
  .then(function(data) {
    document.getElementById("temper").innerHTML="Temperature:" + data.main.temp;
  })
  .catch(function(error) {
    console.log("error: " + error);
  });
}

getLocation();

答案 1 :(得分:0)

使用它:

function getLocation() {
    if (navigator.geolocation)
       navigator.geolocation.getCurrentPosition(showPosition); 
}

function showPosition(position) {
    var la= position.coords.latitude;
    var lg= position.coords.longitude;
    fetchTemperature(la, lg); // create a method for fetch temperature and send la and lg to it
}

function fetchTemperature(la, lg){ // method for fetch temperature
    var url="https://fcc-weather-api.glitch.me/api/current?lat=" + la + "&lon=" + lg;
    document.getElementById("im").innerHTML="Latitude:" + la;

    fetch(url)
     .then((resp) => resp.json())
     .then(function(data) {
         document.getElementById("temper").innerHTML="Temperature:" + data.main.temp;
    })
    .catch(function(error) {
        console.log("error: " + error);
    });
}

getLocation();