본문 바로가기
개인 프로젝트/[Web] 날씨 위젯 홈페이지 프로젝트

[개인 프로젝트] 날씨 api 온도 측정 단위 °C

by 뿌비 2022. 5. 1.
728x90
날씨 위젯 홈페이지 개인 프로젝트에서 사용한 날씨 api 주소  https://openweathermap.org/

작성하게 된 이유 

  • api 사용경험이 별로 없어서 사용 방법 문서를 봐도 잘 이해가 안돼서 놓치는 부분이 있었다 그런 점을 적어 두려고 작성하게 되었다.

문제 상황

  • api로 데이터를 받아 왔는데 온도(temp)가 섭씨로 나와야 하는데  화씨로 나와서 어떻게 변환해야 하는 건지 의문이었다


해결 

  • 해결 방법은 생각보다 간단했다 마음을 비우고 그냥 문서를 차근차근 잘 읽어보면 된다.............
  • api를 호출할 때  API key  뒤에  & 하고 units=metric라고 설정을 해주면 우리가 원하는 섭씨로 변환되서 사용할 수 있다 
// 예시
promiseGet('https://api.openweathermap.org/data/2.5/weather?q=날씨검색지역작성&appid=APIkey작성&units=metric')
    .then(res => console.log(res))
    .catch(err => console.log(err));


변환된 모습 

화씨 -> 섭씨로 변환


Math.floor()   섭씨 온도 소수점 버림

  • 17 °C 이렇게 보여지게 하기 위해서 소수점을 버리는 Math.floor() 를 사용했다 
// api 를 받아와서 출력하는 코드일부(필요없는 부분 생략)
promiseGet('https://api.openweathermap.org/data/2.5/weather?q=지역&appid=APIKey&units=metric')
.then(function (response) { 
	// Math.floor를 사용해서 섭씨온도의 소수점은 다 버려주었다 
    const seoul_temperature = Math.floor(response.main.temp);
    document.querySelector('.seoul').innerHTML = `${seoul_temperature}°C`;
  });

 

728x90