JS Project:WeatherJS

UI

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="bootstrap.min.css">
  <title>Weather JS</title>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-md-6 mx-auto text-center bg-primary mt-5 p-5 rounded">
        <h1 id="w-location"></h1>
        <h3 class="text-dark" id="w-desc"></h3>
        <h3 id="w-string"></h3>
        <img id="w-icon">
        <ul class="list-group mt-3" id="w-details">
          <li class="list-group-item" id="w-humidity"></li>
          <li class="list-group-item" id="w-dewpoint"></li>
          <li class="list-group-item" id="w-feels-like"></li>
          <li class="list-group-item" id="w-wind"></li>
        </ul>
        <hr>
                  <!-- Button trigger modal -->
          <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#locModel">
            Change Location
          </button>
      </div>
    </div>
  </div>
  <!-- Modal -->
  <div class="modal fade" id="locModel" tabindex="-1" role="dialog" aria-labelledby="locModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="locModalLabel">Choose Location</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form id="w-form">
            <div class="form-group">
              <label for="city">City</label>
              <input type="text" id="city" class="form-control">
            </div>
            <div class="form-group">
              <label for="Country">Country</label>
              <input type="text" id="country" class="form-control">
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button id="w-change-btn" type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>



  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>


<script src="storage.js"></script>
<script src="ui.js"></script>
<script src="weather.js"></script>
<script src="app.js"></script>
</body>
</html>

使用API调取城市的天气信息

在这里插入图片描述
创建Weather类,通过api得到天气信息

class Weather{
  constructor(city,country){
    this.apiKey='*';
    this.city = city;
    this.country=country;
  }

  //Fetch weather from api
  async getWeather(){   //要把http加上
    const response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${this.city},${this.country}&APPID=${this.apiKey}`);

    const responseData= await response.json();
    return responseData;
  }

  //Change weather location
  changeLocation(city,country){
    this.city=city;
    this.country=country;
  }
}

调用weather类,fetch天气信息

DOMContentLoaded使得页面加载时就得到天气信息;

//Init weather class
const weather = new Weather(`Boston`,`US`);


//Get weather on dom load
document.addEventListener('DOMContentLoaded',getWeather);


function getWeather(){
    weather.getWeather()    //使用asnyc 返回promise,需要用then返回object
          .then(results=>console.log(results))
          .catch(err=>console.log(err));
}

设置UI类,将信息填入UI中

class UI{
  constructor(){
    this.location = document.getElementById('w-location');
    this.desc = document.getElementById('w-desc');
    this.string = document.getElementById('w-string');
    this.icon = document.getElementById('w-icon');
    this.details = document.getElementById('w-details');
    this.humidity = document.getElementById('w-humidity');
    this.dewpoint = document.getElementById('w-dewpoint');
    this.feels_like = document.getElementById('w-feels-like');
    this.wind = document.getElementById('w-wind');
    
  }

  paint(weather){
    this.location.textContent=`${weather.sys.country},${weather.name}`;
    this.desc.textContent=weather.weather[0].description;
    this.string.textContent=`${weather.main.temp} F`;
    this.icon.setAttribute(`src`,`http://openweathermap.org/img/wn/${weather.weather[0].icon}@2x.png`);
    this.humidity.textContent=`Relative Humidity : ${weather.main.humidity} %`;
    this.feels_like.textContent=`Feels Like : ${weather.main.feels_like} F`;
    this.dewpoint.textContent=`Pressure : ${weather.main.pressure} pa`;
    this.wind.textContent=`Wind Speed: ${weather.wind.speed} m/s`;
  }
}
//Init weather class
const weather = new Weather(`Boston`,`US`);

//Init UI
const ui = new UI();
//Get weather on dom load
document.addEventListener('DOMContentLoaded',getWeather);



//weather.changeLocation('hangzhou','cn');

function getWeather(){
    weather.getWeather()    //使用asnyc 返回promise,需要用then返回object
          .then(results=>{
            ui.paint(results);
          })
          .catch(err=>console.log(err));
}

设置localstorage,保存设置的city和country

storage.js

class Storage{
  constructor(){
    this.city;
    this.country;
    this.defaultCity=`Miami`;
    this.defaultCountry='US';
  }

  getLocationData(){
    if(localStorage.getItem('city')===null){
      this.city=this.defaultCity;
    }else{
      this.city=localStorage.getItem('city');
    }
    if(localStorage.getItem('country')===null){
      this.country=this.defaultCountry;
    }else{
      this.country=localStorage.getItem('country');
    }
    return {
      city: this.city,
      country:this.country
    }
  }

  setLocationData(city,country){
    localStorage.setItem("city",city);
    localStorage.setItem("country",country);
  }
}

ui.js

class UI{
  constructor(){
    this.location = document.getElementById('w-location');
    this.desc = document.getElementById('w-desc');
    this.string = document.getElementById('w-string');
    this.icon = document.getElementById('w-icon');
    this.details = document.getElementById('w-details');
    this.humidity = document.getElementById('w-humidity');
    this.dewpoint = document.getElementById('w-dewpoint');
    this.feels_like = document.getElementById('w-feels-like');
    this.wind = document.getElementById('w-wind');
    
  }

  paint(weather){
    this.location.textContent=`${weather.sys.country},${weather.name}`;
    this.desc.textContent=weather.weather[0].description;
    this.string.textContent=`${weather.main.temp} F`;
    this.icon.setAttribute(`src`,`http://openweathermap.org/img/wn/${weather.weather[0].icon}@2x.png`);
    this.humidity.textContent=`Relative Humidity : ${weather.main.humidity} %`;
    this.feels_like.textContent=`Feels Like : ${weather.main.feels_like} F`;
    this.dewpoint.textContent=`Pressure : ${weather.main.pressure} pa`;
    this.wind.textContent=`Wind Speed: ${weather.wind.speed} m/s`;
  }
}

weather.js

class Weather{
  constructor(city,country){
    this.apiKey='*';
    this.city = city;
    this.country=country;
  }

  //Fetch weather from api
  async getWeather(){   //要把http加上
    const response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${this.city},${this.country}&APPID=${this.apiKey}`);

    const responseData= await response.json();
    return responseData;
  }

  //Change weather location
  changeLocation(city,country){
    this.city=city;
    this.country=country;
  }
}

app.js

//Init storage
const storage= new Storage();
//Get stored location data
const weatherLocation = storage.getLocationData();

//Init weather class
const weather = new Weather(weatherLocation.city,weatherLocation.country);

//Init UI
const ui = new UI();

//Get weather on dom load
document.addEventListener('DOMContentLoaded',getWeather);

//Change location event
document.getElementById('w-change-btn').addEventListener('click',(e)=>{
  const city=document.getElementById('city').value;
  const country=document.getElementById('country').value;

  //Change location
  weather.changeLocation(city,country);
  //Set location in local storage
  storage.setLocationData(city,country);

  //Get and display weather again
  getWeather();

  //Close model
  $("#locModal").modal('hide');
})

//weather.changeLocation('hangzhou','cn');

function getWeather(){
    weather.getWeather()    //使用asnyc 返回promise,需要用then返回object
          .then(results=>{
            ui.paint(results);
          })
          .catch(err=>console.log(err));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值