[Open API] openweathermap api 이용

Noah97·2022년 7월 12일
0

open api를 이용하여 날씨 정보를 받아오기

<!DOCTYPE html>
<html>
<head>
  <title>weather api</title>
</head>
<style>
  * {
    margin: 0 auto;
  }
  .card {
    margin-top: 20px;
    width: 300px;
    height: 400px;
    background-color: lightgray;
    text-align: center;
  }
  #humidity {
    line-height: 50px;
    font-size: x-large;
  }
  #ic {
    width: 70px;
    height: 70px;
  }
</style>
<body>
    <div class = "card">
      <h2>수원시</h2>
      <img id = "ic" src="">
      <br>
      <span id="humidity"></span>
    </div>
    <script>
      let url = "https://api.openweathermap.org/data/2.5/weather?q=Suwon&appid={사용자api키}&units=metric"

      fetch(url)
        .then((response) => {
          return response.json();
        })
        .then((json) => {
          console.log(json);
  
          let result = "온도 : " + Math.floor(json.main.temp) + "ºC<br>" //소수점 버림 온도를 찍어줌
                      + "습도 : " + json.main.humidity + "%<br>" //습도를 찍어줌
                      + "바람 : " + json.wind.speed + "m/s<br>" //풍속을 찍어줌
                      + "최고온도 : " +Math.floor(json.main.temp_max) + "C<br>" //소수점 버림 온도를 찍어줌
                      + "최저온도 : " +Math.floor(json.main.temp_min)  + "ºC" //소수점 버림 온도를 찍어줌
          let icon = json.weather[0].icon; //아이콘 받아옴
        document.getElementById("humidity").innerHTML = result; //result를 humidity라는 id를 가진 span에 innerHTML로 표시
        let iconurl = document.getElementById('ic'); //img id를 iconurl이라는 이름으로 받아옴
        iconurl.src = "http://openweathermap.org/img/wn/" + icon + ".png"; //iconurl로 src를 설정해줌
        });
    </script>
    </body>
  </html>

실행 화면

profile
안녕하세요 반갑습니다😊

0개의 댓글