본문으로 건너뛰기
poylog

개발·AI

날씨 API

2분

API 배우고 연습할만한 주제를 찾다가 날씨 위젯을 만들어 보려다가 괜찮은 코드를 발견했다

따라 만들어보면서 몰랐던 부분이나 안 되는 부분에 대한 피드백을 해보려 한다

부산 8°C·Broken Clouds가 표시된 날씨 위젯 초기 화면

1. html 작성

1)  head

head 부분에 가져올 링크들을 넣어주고 시작했다

html
  <link rel="stylesheet" href="./style.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">  /// 폰트는 css에서 불러올 수 있지 않았나..
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>  
  <link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet
  <script src="./script.js"></script>

코드를 다 작성하고 열어보니 자바스크립트가 적용이 안되고, 콘솔창에

script.js 27행 addEventListener null 타입 오류가 뜬 브라우저 콘솔

이런 오류가 떴다.

구글링 해보니 html이 로드되기 전에 자바스크립트 영역이 html을 참조했기 때문이라고 한다.

단순히 순서 문제였기 때문에 body 하단으로 자바스크립트 링크를 옮겨주는 걸로 해결했다

html
  <script src="./script.js"></script>
</body>

2) 버튼 아이콘

vscode 확장자로 React Icons를 다운 받아서 쉽게 아이콘을 가져와 사용할 수 있었다

React Icons에서 search 키워드 돋보기 아이콘 검색 결과 그리드

svg를 복사한 다음 붙여 넣기만 하면 돼서 자주 사용할 것 같다

html
<button>
        <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0 0 11.6 0l43.6-43.5a8.2 8.2 0 0 0 0-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z"></path></svg>
      </button>

2. CSS

1) 배경 이미지

css
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background: rgb(41, 39, 39);
  font-family: 'Open Sans', sans-serif;  
  background-image: url(https://source.unsplash.com/random/1600x900/?weather); 
  background-size: 100% 100%;
}

배경 url에는 unsplash에서 제공하는 랜덤 이미지를 사용했다

날씨 위젯이라 weather를 사용했지만 저 자리에 landscape나 technology 등 다양한 테마의 랜덤 사진을 가져올 수 있다

unsplash에서 제공하는 API를 사용하는 방법도 익혀보자

3. JavaScript

1) API 사용

javascript
let weather = {
  "apiKey" : "my api",
  fetchWeather : function (city) {
    fetch("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&usits=metric&appid=" + this.apiKey)
    .then((response) => response.json())
    .then((data) => this.displayWeather(data));
  }, //api에서 정보를 가져온 후 사용 할 수 있게 data로 넘김
  displayWeather : function (data) {
    const {name} = data;
    const {icon, description} = data.weather[0];
    const {temp,humidity} = data.main;
    const {speed} = data.wind;
    console.log(name,description,icon,temp,humidity,speed);
    document.querySelector(".city").innerText = "Weather in " + name;
    document.querySelector(".description").innerText = description;
    document.querySelector(".temp").innerText = Math.round(temp - 273) + "℃";
    document.querySelector(".humidity").innerText = "Humidity: " + humidity + "%";
    document.querySelector(".wind").innerText = "Wind speed: " + speed + "km/h";
    document.querySelector(".weather").classList.remove("loading");
  }, //데이터를 어떻게 표기할 지
  search: function() {
    this.fetchWeather(document.querySelector(".search-bar").value);
  } // 검색창에 검색한 도시이름이 fetchWeather에 들어갈 수 있도록
};

원래 코드에서는. temp로 가져온 온도가 절대온도로 표기되어서 절대온도에 대해서도 알게 되었다

부산 날씨가 절대온도 280.14°C로 잘못 표시된 위젯 화면

부산을 불바다로 만들어버린..

-273도를 해주면 섭씨와 같아지고, 소수점이 엄청 많았기에 반올림도 해주었다

2) 검색 버튼

아까 만들어둔 돋보기 아이콘을 눌렀을 때와 검색 칸에 입력 후 엔터키를 눌렀을 때, 바로 search로 값이 들어갈 수 있게 만들었다

javascript
document.querySelector(".search button").addEventListener("click", function() {
  weather.search();
});
document.querySelector(".search-bar").addEventListener("keyup",function(event) {
  if (event.key == "Enter") {
    weather.search()
  }

조금 더 간결하게 작성할 수 있는 방법이 있는지 알아봐야겠다

참조 : https://www.codewithrandom.com/2022/03/weather-app-using-html-css-and.html