Web Front-end/javaScript
날씨(openWeather) API로 날씨정보 가져오기
develop_study
2023. 3. 22. 23:50
반응형
openWeather API로 현재 날씨정보를 가져오기.
1. openWeather 사이트 접속, 현재 날씨를 가져올수 있는 api인 current Weather Data를 참조한다.
https://openweathermap.org/current
2. 날씨를 불러올수 있는 방법이 아래와 같이 나와있다.
여기서 api키는 회원가입 후 my api keys를 확인하면 된다.
https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
3.우선 현재 장치의 위치를 가져와야한다. 다음은 브라우저에서 제공하는 JS의 Geolocation API 메서드이다.
success와 error 부분은 콜백함수로 position을 매개변수로 받을수있다.
navigator.geolocation.getCurrentPosition(success, error, [options])
4. 다음과 같이 successCallback에 매개변수를 console.log로 찍어보면 현재 장치의 위도와 경도 값을 얻을 수 있다.
const callbackOk= (position) =>{
console.log(position)
const lat = position.coords.latitude //위도
const lon = position.coords.longitude //경도
}
navigator.geolocation.getCurrentPosition(callbackOk, callbackError)
5. 처음에 확인했던대로 api를 불러와 console.log로 찍어보면 다음과 같은 결과 값을 얻을 수 있다.
const API_KEY = '내 api키'
const callbackOk= (position) =>{
const lat = position.coords.latitude //위도
const lon = position.coords.longitude //경도
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`
console.log(url)
}
활용할 객체로는 name, main.temp, weather.description, wind.speed, wind.degree 정도 되겠다.
추가로 lang, units를 파라미터로 받을수있다. 언어설정과 측정단위를 설정할 수 있다.
6. 완성
//weather.js
import { API_KEY } from "./api_key.js"
const city = document.querySelector('.weather tbody td:first-child')
const weather = document.querySelector('.weather tbody td:nth-child(2)')
const temp = document.querySelector('.weather tbody td:nth-child(3)')
const wind = document.querySelector('.weather tbody td:nth-child(4)')
const degToCompass = (num) => {
const val = Math.floor((num / 22.5) + 0.5);
const arr = ['북', '북북동', '동북동', '동동북', '동', '동동남', '남동', '남남동', '남', '남남서', '서남서', '서서남', '서', '서북서', '북서', '북북서'];
return arr[(val % 16)];
}
const callbackOk= (position) =>{
const lat = position.coords.latitude //위도
const lon = position.coords.longitude //경도
const lang = 'kr' //언어
const units = 'metric' //섭씨
console.log(`현재 위도 및 경도 : $${lat}, ${lon} `)
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&lang=${lang}&units=${units}&appid=${API_KEY}`
// console.log(url)
fetch(url)
.then(response => response.json())
.then(data=>{
const temperature = Math.round(data.main.temp)
const windDirection = degToCompass(data.wind.deg)
city.innerText = data.name
weather.innerText = data.weather[0].description
temp.innerText = `${temperature}도`
wind.innerText = `${windDirection} ${data.wind.speed}m/s`
})
}
const callbackError= () =>{
alert("위치정보를 찾을 수 없습니다.")
}
// 사용자의 현재 위치정보를 가져옴
navigator.geolocation.getCurrentPosition(callbackOk, callbackError) //getCurrentPosition(successCallback, errorCallback, options)
//index.html
<!DOCTYPE html>
<head>
<script src="./js/api_key.js" type="module"></script>
<style>
.weather {
border-collapse: collapse;
}
.weather thead td {
border: 1px solid #000;
background-color: #ccc;
padding: 5px;
}
.weather tbody td {
border: 1px solid #000;
padding: 5px;
border-right: 1px solid #ccc;
}
.weather tbody td:first-child {
text-align: center;
}
</style>
</head>
<body>
<table class="weather">
<thead>
<td>지역</td>
<td>날씨</td>
<td>온도</td>
<td>풍향/풍속</td>
</thead>
<tbody>
<td></td>
<td></td>
<td></td>
<td></td>
</tbody>
</table>
<script src="./js/weather.js" type="module"></script>
</body>
</html>
# 참고 :
https://openweathermap.org/current
https://developer.mozilla.org/ko/docs/Web/API/Geolocation/getCurrentPosition
반응형