使用Javascript获取天气数据(来自darksky)

时间:2019-02-22 19:05:44

标签: javascript geolocation fetch-api

大家好,我想从darksky获取天气api,我有天气类,并在其构造函数中定义了apikey,city(我现在不使用),long和lat(用于协调)。我想获得浏览器的地理位置并将其传递给long和lat变量。我说这句话时出现错误

“未捕获的ReferenceError:未定义long”您能告诉我问题出在哪里吗?

class Weather {
  constructor() {
    this.apiKey = 'xxxx';
    this.city = city;
    this.long = long;
    this.lat = lat;
  }

  //Fetch from API
  async getWeather() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        clearTimeout(location_timeout);
        this.long = position.coords.longitude;
        this.lat = position.coords.latitude;
      });
      console.log(this.long, this.lat);
      const response = await fetch(`https://api.darksky.net/forecast/${this.apiKey}/${this.lat},${this.long}`);
      const responseData = await response.json();
      return responseData.current_observation;
    }
  }

}
const weather = new Weather();

weather.getWeather()
       .then(results => {
         console.log(results);
       })
       .catch(err => console.log(err));

0 个答案:

没有答案