◼ API key 받는 법
- https://openweathermap.org/에 회원가입합니다.
- 로그인 후 오른쪽 상단 "사용자이름"을 클릭합니다.
- "My API keys"버튼을 선택합니다.
- "API keys"탭에서 나의 API key를 확인합니다.
◼ 예제
html
<html>
<body>
<button class="button">버튼</button>
<div>위치 : <span class="weather-location"></span></div>
<div>기온 : <span class="weather-temperature"></span></div>
<div>날씨 : <span class="weather-description"></span><img class="weather-icon" /></div>
</body>
</html>
javascript
const button = document.querySelector(".button");
button.addEventListener("click", () => {
const API_KEY = "API_KEY값";
const weatherLocation = document.querySelector(".weather-location");
const weatherTemperature = document.querySelector(".weather-temperature");
const weatherDescription = document.querySelector(".weather-description");
const weatherIcon = document.querySelector(".weather-icon");
const success = (position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
getWeather(latitude, longitude);
};
const fail = () => {
alert("위치 권한이 거부 되었습니다.");
};
navigator.geolocation.getCurrentPosition(success, fail);
const getWeather = (lat, lon) => {
fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric&lang=kr`)
.then((response) => {
return response.json();
})
.then((json) => {
console.log(json);
const location = json.name;
const temperature = json.main.temp;
const description = json.weather[0].description;
const icon = json.weather[0].icon;
const iconURL = `http://openweathermap.org/img/wn/${icon}@2x.png`;
weatherLocation.innerText = name;
weatherTemperature.innerText = temperature;
weatherDescription.innerText = description;
weatherIcon.setAttribute("src", iconURL);
})
.catch((error) => {
alert(error);
});
};
});