날씨 정보를 가져오기 위해 API를 사용.
openweathermap.org/
С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 global and local weather models, satellites, radars and vast network of weather stations. how to obtain APIs (subscriptions with di
openweathermap.org
회원가입 - API keys 클릭 (아래 Key는 유효하지 않습니다.)

현재 날씨 데이터
openweathermap.org/current
Current weather data - OpenWeatherMap
Access current weather data for any location on Earth including over 200,000 cities! We collect and process weather data from different sources such as global and local weather models, satellites, radars and vast network of weather stations. Data is availa
openweathermap.org

위의 코드를 이용해서 API를 호출 할 수 있습니다.
<html />
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Weather & Location</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<span class="js-weather"></span>
<script src="weather.js"></script>
</body>
</html>
<javascript />
// weather.js
const weather = document.querySelector(".js-weather");
// const API_KEY = "API KEY 입력";
const COORDS = "coords";
function getWeather(lat, lng) {
fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}`
)
.then(function (response) { // .then = fetch가 완료 된 후 실행됨
return response.json(); // json형태로 변환
})
.then(function (json) {
const temperature = json.main.temp;
const place = json.name;
weather.innerText = `${temperature} @ ${place}`;
});
}
function saveCoords(coordsObj) { // localStorage에 저장
localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}
function handleGeoSucces(position) { // 요청 수락
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const coordsObj = {
latitude,
longitude,
};
saveCoords(coordsObj); // localStorage에 저장 함수
}
function handleGeoError() { // 요청 거절
console.log("Not allowed.");
}
function askForCoords() { // 사용자 위치 요청 (요청 수락, 요청 거절)
navigator.geolocation.getCurrentPosition(handleGeoSucces, handleGeoError);
}
function loadCoords() {
const loadedCoords = localStorage.getItem(COORDS); // localStorage에서 위치정보 가져옴
if (loadedCoords === null) { // 위치 정보가 없으면
askForCoords(); // 위치 정보 요청 함수
} else {
const parseCoords = JSON.parse(loadedCoords); // json형식을 객체 타입으로 바꿔서 저장
getWeather(parseCoords.latitude, parseCoords.longitude); // 날씨 요청 함수
}
}
function init() {
loadCoords();
}
init();
<css />
/* index.css */
body {
background-color: peru;
}
.js-weather {
margin-left: 30px;
color: white;
font-size: 40px;
}


'JavaScript' 카테고리의 다른 글
JavaScript 기본 (0) | 2023.03.12 |
---|---|
[JavaScript] 조건부 연산자, AND 연산자, OR 연산자 (0) | 2021.03.05 |
[JavaScript] 배경이미지 설정 (0) | 2020.12.23 |
[JavaScript] to do list 만들기 (localStorage) (2) | 2020.12.23 |
[JavaScript] localStorage 사용 (0) | 2020.12.22 |