-
🌪 OpenWeather API 사용하기으쌰으쌰 2023. 6. 2. 19:16
말그대로 OpenWeather API를 사용해봤다.
나중에 까먹었을 때 바로 찾을 수 있도록 기록해둔다.
1. 회원가입 > 로그인
2. myAPIkey 로 가서 API 복붙 해두기.
3. Curren Weather Data
그밖에도 여러가지 API가 존재하지만
1. 현재 위치정보를 받아온다.
2. 지역명, 온도, 날씨(맑음, 흐림, 비..등등)
을 사용하고 싶었기 때문에 Current Weather Data 를 사용했다.
4. API call
아주 친절하게 API를 부를 url을 알려주고 있다.
여기서 알아야 할 세 가지의 정보를 알 수 있다.
1. lat (latitude :위도)
2. lon (lolongitude :경도)
3. API key
이다. 3번 API key는 위에서 복붙해놨던 걸 사용한다.
5. 현재 위치의 위도와 경도(lat & lon) 알아내기
const getCurrentLocation = () => { navigator.geolocation.getCurrentPosition((position) => { const lat = position.coords.latitude; const lon = position.coords.longitude; }); };
navigator.geolocation.getCurrentPosition()을 이용했다.
6. 알아낸 정보를 사용해서 API 사용하기
const getWeatherCurrentLocation = (lat, lon) => { const key = '~~~~~'; const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${key}`; console.log(url); fetch(url) .then((response) => response.json()) .then((data) => { console.log(data.weather[0]); const weather = data.weather[0].main; const temp = data.main.temp; const city = data.name; const span = document.getElementById('weather'); span.innerText = `${city}, ${(temp - 273.15).toFixed(1)}°, ${weather}`; }); };
✍️ json 을 확인해보면 온도를 캘빈값으로 표시하고 있는 걸 알 수 있다. 섭씨 온도로 바꾸기 위해 273.15를 빼고 toFixed()를 사용해서 수많은 소수점자리들을 하나만 나타나게 만들었다.
'으쌰으쌰' 카테고리의 다른 글
바닐라JS 로 만드는 북마크 웹앱 📓 (2) 게시물 편 (0) 2023.02.04 바닐라JS 로 만드는 북마크 웹앱 📓 (1) 회원가입, 로그인 편 (0) 2023.01.25 바닐라JS 로 만드는 북마크 웹앱 📓 (0) 계획 편 (0) 2023.01.24 localStorage 를 이용해서 로그인 / 회원가입 구현하기! (3) 수정, 추가 마지막 정리 편 (1) 2023.01.21 localStorage 를 이용해서 로그인 / 회원가입 구현하기! (2) 로그인 편 (0) 2023.01.20