오픈웨더맵 : https://openweathermap.org/api
사용자가 있는 위치정보를 받아 날씨를 알려주는 기능이다.
날씨를 알기 위해서는 API서버에서 날씨정보를 받아와야 하는데
위에 링크에 사이트에서 날씨 정보를 받아올 수 있다.
날씨 보여주기 기능을 구현하기 위해서는 API서버와 연동하는 방법, 위치정보를 받는 방법을 알아야한다.
위치정보를 먼저 받아온다. 자바스크립트에 이미 내장되어있는 navigator.geolocation
메서드를 사용하면 브라우저에서 위치정보를 보여준다.
navigator.geolocation.getCurrentPosition(onGeoOK, onGeoError);
getCurrentPosition메서드는 두개의 매개변수를 받는데 첫번째는 위치정보를 받는데 성공했을 때 실행할 함수, 두번째는 위치정보를 받는데 실패했을 때 실행할 함수이다.
const API_KEY = "1234567890abcdefghijk"; //API KEY를 사이트에서 받아와야한다.
function onGeoOK(posision) {
const lat = posision.coords.latitude;
const lon = posision.coords.longitude;
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&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.textContent = data.name;
weather.textContent = `${data.weather[0].main} / ${Math.round(data.main.temp)}°C`;
});
}
function onGeoError() {
alert("can't find you. No weather for you.");
}
위치정보를 받는데 성공하면 onGeoOK
함수를 실행한다.
그 때 브라우저에서는 어떤 객체를 넘겨주는데 그 객체에는 위도,경도 위치 정보가 있다.
그 정보를 각각 lat, lon 변수에 담아준 후 API URL에 담아준다.
API에서 받아온 정보 중 도시이름, 날씨정보를 받아온 후 html에 출력한다.