[Javascript] weather API - 날씨정보 가져오기
내가 있는 장소의 날씨 정보를 얻기 위하여 weather API 를 활용할 것이다.
Сurrent weather and forecast - OpenWeatherMap
Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w
openweathermap.org
해당 홈페이지에서 무료 Weather API 를 제공한다. 하지만 사용하기 위하여 로그인이 필요하다. 누구나 편하게 회원가입할 수 있도록 되어있기 때문에 걱정할 필요는 없다.
회원가입 한 후, 회원가입 시 입력한 이메일로 가서 본인확인을 해줘야 API KEY를 얻을 수 있다!!
Javascript 에서 geolocation object 를 제공해준다. 이를 사용하여 날씨정보를 가져오는 기능을 구현할 것이다.
navigator.geolocation.getCurrentPosition(성공함수, 실패함수)
navigator.geolocation.getCurrentPosition 은 웹페이지에서 위치정보를 가져올 수 있게 하는 기능을 가지고 있다.
성공함수 : 위치정보를 성공적으로 가져왔을 때 실행하는 함수
실패함수 : 위치정보 가져오는 것을 실패했을 때 실행하는 함수
const API_KEY = "weather 홈페이지에서 API KEY 가져오기"
function onGeoOk(position) { //geolocation object
const lat = position.coords.latitude; //위도 정보
const log = position.coords.longitude; //경도 정보
console.log(lat,log)
const link = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${log}&appid=${API_KEY}`
// API 를 통해 날씨 객체를 받아옴.
fetch(link).then(response => response.json()).
then(data => {
const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
weather.innerText = data.name;
city.innerText = `${data.weather[0].main} / ${data.main.temp}`
});
// JS가 정보받아와줌
//fetch 는 promise로 바로 일어나는 과정이 아닌 시간경과가 필요함(서버응답시간필요)
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);
//API 활용. weather API
다음 포스트에서는 fetch 에 대한 정보를 포스팅 할 것이다. fetch 는 Javascript 를 사용하여 웹페이지를 열지않고도 웹서버에 접근하고 필요한 정보를 가져올 수 있게 하는 API 이다.