📍 Javascript를 공부했을 때 학습노트에 정리해둔 것을 옮겨왔다.
우리가 원하는 json object를 가져오기 위해서는 .then 을 한번 더 사용해야한다.
function getWeather(lat, lon) {
fatch (
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=units=metric`
// json 데이터 가져오기 1
) .then(function (response) {
return response.json();
})
// json 데이터 가져오기 2
) .then(function (json) {
console.log(json);
});
}
console.log(json); 실행결과
Step 4. JSON 데이터에서 가져온 결과를 웹페이지에 구현하기
<span class="js-weather"></span>
const weather = document.querySelector(".js-weather");
const API_KEY = "4842c80ba1638386637c9f75890d81a7";
const COORDS = 'coords’;
function getWeather(lat, lon) {
fatch (
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=units=metric`
) // json 데이터 가져오기 1
.then(function (response) {
return response.json();
}) // json 데이터 가져오기 1
.then(function (json) {
const temperature = json.main.temp;
const place = json.name;
weather.innerText = `${temperature} @ ${place}`;
});
/* then()이 하는 역할은 기본적으로 함수를 호출하는 것이지만, fetch를 실행한 이후(API 데이터가 완전히 들어오고 난) 이후에 호출하는 것이다. */
}
function saveCoods(coordsObj){
localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}
function handleGeoSucces(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const coordsObj = {
latitude,
longitude
};
saveCoods(coordsObj);
getWeather(latitude, longitude);
}
function handleGeoError(){
console.log("can't accese geo location");
}
function askForCoords() {
navigator.geolocation.getCurrentPosition(handleGeoSucces, handleGeoError);
}
function loadCoords() {
const loadedCoords = localStorage.getItem(COORDS);
if (loadedCoords === null) {
askForCoords();
} else {
const parseCoords = JSON.parse(loadedCoords);
getWeather(parseCoords.latitude, parseCoords.longitude)
}
}
function init() {
loadCoords();
}
init();
tip. 버튼 외곽선 없애주는 css 명령어
button {
all: unset;
}