본문 바로가기
jQuery

날씨 위젯

by hjcode 2019. 10. 11.

openweather 날씨 API를 통해 날씨 위젯을 만들었습니다.

openweather API는 AJAX요청을 통해 해당 위치의 날씨 정보를 JSON으로 반환해줍니다.

 

<div id="weather_info">
   <h1 class="city"></h1>

   <section>
      <p class="w_id"></p>
      <figure class="icon"></figure>
      <p class="temp"></p>
      <aside>
         <p class="temp_max">max</p>
         <p class="temp_min">min</p>
      </aside>
   </section>
   <img src="https://www.vedantaresources.com/SiteAssets/Images/loading.gif" alt="" id="load_img">
</div>

 

* {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
}

body {
   color: #333;
}

p {
   margin: 0 0 10px;
}

#weather_info {
   position: relative;
   padding: 10px;
   margin: 0 auto;
   width: 50%;
   height: 310px;
   background: url(https://www.wired.com/wiredenterprise/wp-content/uploads//2013/02/clouds.jpg) no-repeat #eee 50% / cover;
   border: 1px solid #999;
   color: #fff;
}

h1 {
   padding: 10px;
   font-size: 1.8em;
   background: #666;
   text-align: center;
   opacity: 0.8;
}

section {
   padding: 10px 20px;
   overflow: hidden;
   color: #fff;
   text-shadow: 1px 1px 1px #999;
}

.w_id {
   text-align: left;
}

.temp {
   float: left;
   width: 33.3333%;
   font-size: 4em;
}

figure img {
   width: 80px;
}

aside {
   overflow: hidden;
}

aside p {
   font-size: 1.8em;
   text-align: right;
}

#load_img {
   display: none;
   position: absolute;
   left: 50%;
   top: 50%;
   width: 100px;
   height: 100px;
   transform: translate(-50%, -50%);
}

 

var url = 'http://api.openweathermap.org/data/2.5/weather?q=seoul&APPID=ef7e4754ad9e63a695df556b89943155';
var loadImg = $('#load_img');

loadImg.show();

$.getJSON(url, function(data) {

      var sys = data.sys; // 국가명, 일출/일몰
      var city = data.name; // 도시명
      var weather = data.weather; //날씨 객체
      var main = data.main; // 온도, 기압 관련 객체

      var wmain = weather[0].main; // 구름상태
      var wId = weather[0].id; // 날씨 상태 id 코드
      var icon = weather[0].icon; // 날씨 아이콘
      var country = sys.country; // 국가명
      var temp = main.temp; // 현재온도
      var tempMin = main.temp_min; // 최저 온도
      var tempMax = main.temp_max; // 최고 온도
      // 온도는 국제단위인 켈빈값이여서 -273.15를 빼줘서 섭씨로 바꿈

      var iconUrl = 'http://openweathermap.org/img/w/' + icon;

      var wrap = $('#weather_info');

      wrap.find('.city').html(city + '/' + country);
      wrap.find('.icon').html('<img src=" ' + iconUrl + '.png ">');
      wrap.find('.w_id').html(wmain);
      wrap.find('.temp_min').html(parseInt(tempMin - 273.15) + '&deg;' + 'min');
      wrap.find('.temp_max').html(parseInt(tempMax - 273.15) + '&deg;' + 'max');
      wrap.find('.temp').html(parseInt(temp - 273.15) + '&deg;');
      loadImg.hide();

   })
   .fail(function() {
      alert('loading error!');
   });

 

'jQuery' 카테고리의 다른 글

숫자 정렬 토글로 만들기  (0) 2019.12.19
jQuery로 간단한 todo 만들기  (0) 2019.11.14
계산기 만들기  (0) 2019.10.02
TweenMax 텍스트 애니메이션  (0) 2019.10.02
TweenMax 눈내리는 효과  (0) 2019.09.28