Getting Weather
5. 날씨 정보 얻기 : Weather API에서 유저의 해당 지역과 온도를 출력
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Something</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="js-clock">
<h1 class="js-title">00:00</h1>
</div>
<form class="js-form form">
<input type="text" placeholder="What is your name?" />
</form>
<h4 class="js-greetings greetings"></h4>
<form class="js-toDoForm">
<input type="text" placeholder="Write a to do" />
</form>
<ul class="js-toDoList">
<script src="clock.js"></script>
<script src="greeting.js"></script>
<script src="todo.js"></script>
<script src="bg.js"></script>
<script src="weather.js"></script>
</body>
</html>
const weather = document.querySelector(".js-weather");
const API_KEY = "450f72e78bda69d216bf82a702bb51b2";
const COORDS = 'coords';
function getWeather(lat, lng){
fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
).then(function(response){
return response.json();
}).then(function(json){
const temperature = json.main.temp;
const place = json.name;
weather.innerText = `${temperature} @ ${place}`;
})
}
function saveCoords(coordsObj){
localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}
function handleGeoSuccess(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const coordsObj = {
latitude,
longitude
};
saveCoords(coordsObj);
getWeather(latitude, longitude);
}
function handleGeoError() {
console.log("Cant access geo location");
}
function askForCoords() {
navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoError);
}
function loadCoords(){
const loadedCoords = localStorage.getItem(COORDS);
if(loadedCoords === null){
askForCoords();
} else {
//getWeather
const parsedCoords = JSON.parse(loadedCoords);
getWeather(parsedCoords.latitude, parsedCoords.longitude);
}
}
function init(){
loadCoords();
}
init();
fetch() 안에는 가져올 데이터가 들어감
ex) `https://~`
*주의 : 따옴표가 아닌 backtick(`)을 사용할 것!
navigator geolocation 메서드를 사용해 latitude(위도), longitude(경도)를 불러올 수 있음
fetch API를 호출할 수 있음
then 기본적으로 함수를 호출하는 것이지만 데이터가 완전히 들어온 다음 호출하는 특징이 있음
Last updated