JS

[JS] weather API and Date

winter17 2023. 7. 2. 17:09

▷ Date

시간을 가져오는 방법은 객체, 반복문을 다룰 줄 알면 굉장히 간단하다.

// Date
const dateElement = document.querySelector('.date')
function todayIsDate(){
  let today = new Date() // Date 객체 생성
  const year = today.getFullYear() // 년도
  const date = today.getDate() // 일
  const month = today.getMonth() + 1 // 월
  const day = today.getDay() // 요일
  
  // 요일을 객체로 변환 
  // 왜? getDay로 받아오면 요일을 0부터 6까지 숫자로 받아오기 때문
  dayObj = {
    0 : 'Sun',
    1 : 'Mon',
    2 : 'Tue',
    3 : 'Wed',
    4 : 'Thu',
    5 : 'Fri',
    6 : 'Sat',
  }
  // dayObj 객체를 반복문 돌려서 day변수와 일치하다면 whichDay 변수에 저장
  let whichDay;
  for (obj in dayObj){
    if (day === parseInt(obj)){
     whichDay = dayObj[obj] 
    } 
  }
// 월도 요일과 마찬가지로 숫자로 받아오는데 문자형태로 바꿔주는 객체 생성
  monthObj = {
    1 : 'Jan.',
    2 : 'Feb.',
    3 : 'Mar.',
    4 : 'Apr.',
    5 : 'May.',
    6 : 'Jun.',
    7 : 'Jul.',
    8 : 'Aug.',
    9 : 'Sep.',
    10 : 'Oct.',
    11 : 'Nov.',
    12 : 'Dec.',
  }
  // 요일과 마찬가지로 반복문 돌려서 일치하면 whichMonth 변수에 저장
  let whichMonth;
  for (obj in monthObj){
    if (month === parseInt(obj)){
      whichMonth = monthObj[obj]
    }
  }
  // 템플릿 리터럴로 화면에 표시할 수 있도록 작성
  dateElement.textContent = `${whichDay} ${whichMonth} ${date} ${year}`
}
// 웹 페이지를 열자마자 이벤트가 실행될 수 있도록
window.addEventListener('DOMContentLoaded', todayIsDate)

 

▷ Weather API

API에 대한 이해가 있어야 하고, fetch에 대해 알고 있어야 하는데 복잡하지만 배운 적이 없다면 쉽진 않다.

// weather

// 날씨 api키는 openweathermap 사이트에서 받아온 후 변수에 저장
const API_KEY = 'fe6747b364df4e73f771db6fb583f92d' 

// 현재 위치를 받아오는데 성공했을 경우
function success(position){
  const latitude = position.coords.latitude // 위도
  const longitude = position.coords.longitude // 경도
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`
  fetch(url)
  .then((response) => response.json())
  .then((data) => {
    const weather = document.querySelector('.today-weather span:nth-of-type(2)')
    const city = document.querySelector('.location span:first-child')
    const temp = document.querySelector('.today-weather span:first-child')
    const humidity = document.querySelector('.today-weather span:last-child')
    const iconEle = document.createElement('img')
    const weatherIcon = data.weather[0].icon
    const iconUrl = `https://openweathermap.org/img/w/${weatherIcon}.png`
    iconEle.src = iconUrl
    temp.innerHTML = ''
    temp.prepend(iconEle)
    temp.append(`${parseInt(data.main.temp)} °C`)
    city.innerText = data.name
    weather.innerText = data.weather[0].description
    humidity.innerHTML = `${data.main.humidity}% Humidity`
    
  })
}
// 현재 위치를 받아오는데 실패했을 경우
function error(){
  alert('죄송합니다. 위치 정보를 사용할 수 없습니다.')
}
// watchPosition 메서드는 위치가 바뀔때마다 자동으로 호출
navigator.geolocation.watchPosition(success, error)

https://openweathermap.org/current

위의 링크를 따라가면 날씨 api를 사용하는 방법을 알 수 있는데 

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}

위의 링크에서 우리가 알아야할건 lat, lon, API key 세 가지이다. 

latitude, longitude, API_KEY 변수로 값을 받아와서 위의 링크에 템플릿 리터럴을 이용하여 넣어주면 된다.

 

fetch(url) // 주어진 URL로 GET요청을 보내고, 이 함수는 Promise 객체를 반환한다.
  .then((response) => response.json()) // 서버로부터 받은 응답(response) 객체를 처리한다.
  .then((data) => {  // 응답 데이터를 처리하는 코드
  	// html에서 작성한 태그를 JS로 불러옴
    const weather = document.querySelector('.today-weather span:nth-of-type(2)')
    const city = document.querySelector('.location span:first-child')
    const temp = document.querySelector('.today-weather span:first-child')
    const humidity = document.querySelector('.today-weather span:last-child')
    const iconEle = document.createElement('img')
    // JSON에서 응답한 객체
    const weatherIcon = data.weather[0].icon // 아이콘은 숫자와 문자의 조합으로 가져오기 때문에
    const iconUrl = `https://openweathermap.org/img/w/${weatherIcon}.png` // 홈페이지에서 제공하는 링크를 통해 이미지를 받아와야 한다.
    iconEle.src = iconUrl
    temp.innerHTML = ''
    temp.prepend(iconEle)
    temp.append(`${parseInt(data.main.temp)} °C`) // 온도
    city.innerText = data.name // 위치
    weather.innerText = data.weather[0].description // 날씨 상세
    humidity.innerHTML = `${data.main.humidity}% Humidity` // 습도

그다음은 fetch 부분인데 fetch() 함수는 비동기 네트워크 요청을 수행하는 함수이다. 

주어진 URL로 HTTP 요청을 보내고, 해당 요청에 대한 응답을 Promise 객체로 반환한다.

 

                          

{
  "coord": {
    "lon": 10.99,
    "lat": 44.34
  },
  "weather": [
    {
      "id": 501,
      "main": "Rain", // 날씨
      "description": "moderate rain", // 날씨 상세 data.weather[0].description
      "icon": "10d" // 아이콘 정보
    }
  ],
  "base": "stations",
  "main": {
    "temp": 298.48, // 온도 data.main.temp
    "feels_like": 298.74,
    "temp_min": 297.56,
    "temp_max": 300.05,
    "pressure": 1015,
    "humidity": 64, // 습도 data.main.humidity
    "sea_level": 1015,
    "grnd_level": 933
  },
  "visibility": 10000,
  "wind": {
    "speed": 0.62,
    "deg": 349,
    "gust": 1.18
  },
  "rain": {
    "1h": 3.16
  },
  "clouds": {
    "all": 100
  },
  "dt": 1661870592,
  "sys": {
    "type": 2,
    "id": 2075663,
    "country": "IT",
    "sunrise": 1661834187,
    "sunset": 1661882248
  },
  "timezone": 7200,
  "id": 3163858,
  "name": "Zocca", // 위치 data.name
  "cod": 200
}

JSON에서 응답한 객체의 정보들 중 필요한 부분만 가져와서 화면에 표시하면 되는데

JSON에서 응답한 객체는 우리 과 같이 생겼다.

 

https://openweathermap.org/weather-conditions

위의 링크는 아이콘을 가져오는 방법에 대한 설명이다.

기본으로 제공하는 아이콘말고 원하는 아이콘으로 변경할 수도 있는데 아직 그 부분은 구현하지 않았다.


openweathermap 홈페이지에서 워낙 꼼꼼하게 설명을 잘해두어서 잘 읽어보면서 따라 하다 보면 할 수 있는 정도이다.