개발/Javascript
[Javascript] Weather API 가져오기
이나당
2022. 9. 5. 09:06
Weather API - OpenWeatherMap
Please, sign up to use our fast and easy-to-work weather APIs. As a start to use OpenWeather products, we recommend our One Call API 3.0. For more functionality, please consider our products, which are included in professional collections.
openweathermap.org
function onGeoOk(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
console.log(`현재 위치는 ${lat}, ${lon}`)
}
function onGeoError() {
alert("날씨를 제공할 위치를 찾을 수 없습니다.")
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
내장함수인 geolocation을 사용해서 현재 좌표를 뽑아냈다.
![](https://blog.kakaocdn.net/dn/bV2J5w/btrLgNIK4jP/nuXwv7n8nsZE9uOyoW2lkk/img.png)
이제 이 위도 경도를 사용해서 현 위치의 날씨를 찾아낼 것이다.
![](https://blog.kakaocdn.net/dn/z9S3p/btrLiBfM0oh/uG7KDguR6Xs3ONtKmu2TW0/img.png)
weather API에 들어가면 대기오염, 날씨 등등 다양한 API정보를 가져올 수 있다.
그중 왼쪽에있는 Current Weather Data를 사용해보자
https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
검색창에 조건에 맞추어서 API를 호출했다
![](https://blog.kakaocdn.net/dn/cmfmax/btrLiq6xVXw/MyIh3vjkeyjO5OvukuA0l1/img.png)
쨔쟌
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`;
API key를 상수로 등록해주고 위도 경도를 url에 입력해준 후 콘솔창으로 코드 출력시 제대로 뜨나 다시확인
![](https://blog.kakaocdn.net/dn/mvVwP/btrLgZWv4Sj/yWRR1OLdl5ixwZxn7CJ0b1/img.png)
![](https://blog.kakaocdn.net/dn/c65FLD/btrLguvXbC7/2MTpDRlMIZuICXYGsB5qjk/img.png)
한국, 용산까지 잘 뜬다.
콘솔이 아닌 fetch를 사용해 네트워크에서 URL확인
![](https://blog.kakaocdn.net/dn/roRds/btrLg8sgrBT/vgM1CONO2obn3UftIIw6nK/img.png)
![](https://blog.kakaocdn.net/dn/d93MQZ/btrLiCMxV71/FCsg8ZfpZSKgjGPDikNkz1/img.png)
![](https://blog.kakaocdn.net/dn/coRAfh/btrLhgDFiA0/gxAV3BYrKObPYb630RbHkk/img.png)
매개변수 확인후 units에서 화씨를 섭씨로 바꾸고 lang 한국어로 설정해주었다.
function onGeoOk(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}&lang=kr&appid=${API_KEY}&units=metric`;
fetch(url)
.then(response => response.json())
.then(data => {
const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
city.innerText = data.name;
weather.innerText = `${data.weather[0].description} / ${data.main.temp}`
});
}
function onGeoError() {
alert("날씨를 제공할 위치를 찾을 수 없습니다.")
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
남은건 css작업... 경희씨 책을 다시 들여다봐야겠다
반응형