자신에게 친절할 것 :)

Web Developing/JS

[JS] 날씨 정보 나타나게 하기 (API사용)

Tashapark 2024. 3. 16. 16:41
728x90

// "Normad Coder의 초보자를 위한 바닐라 JS" 들으며, 모멘텀 클론 코딩 중//

드디어 완강인데,, 석연치 않게 끝나는 느낌..

.then 이해가 전혀 안 돼 ㅠㅜㅠ

휴 쉽지 않은 삶이다 진심...

그래도 완강했다는 것에.. 의의를 두고

담주부터 2주 챌린지 끝내야지 ㅇㅇㅇ

한 번 더 들으면 나아지겠지... ㅎ

css 꾸미는 건 일단 미루고. 하자


<html>

 <body>
    <span class="js-weather"></span>
    <script src="JS/weather.js"></script>
  </body>

 

<js>

const weather = document.querySelector(".js-weather");

const API_KEY = "8be8b30d5f392f273692fd1514c235b1"; // 날씨 api에서 가지고 온 것
// API(appication programming interface; 다른 서버로부터 손쉽게 데이터를 가져올 수 있는 수단. 컴퓨터(machine)끼리 소통하기 위해 고안)
// 그래서 디자인 필요 없음. 걍 데이터만.

function getWeather(lat, lng) {
  fetch(
    `http://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}`;
    });
  // fetch()안에 가져올 데이터를 넣어주면 됌.
  // then 함수를 호출하긴 하지만, 데이터가 완전히 들어온 다음에 호출하는 것.
}
//js는 웹사이트로 request를 보내고 응답을 통해서 데이터를 얻을 수 있는데, 가져온 데이터를 refresh없이 나의 웹사이트에 적용가능하기 때문.
// 그래서 메일 확인할 때 새로고침 안해도 새로운 거 볼 수 있음. js가 뒤에서 계속 정보를 가져오기 떄문에.
// &appid=${API_KEY}를 입력해야 요청자의 api에 엄청 빡세게 요청하지는 않았음을 알 수 있음.
// js 코드 들으래.. 응,, 미친 then,,, 이해 안가.^^
const COORDS = "coords";

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, // 변수의 이름과 객체의 key를 같게 할 때는 latitude: latitude 이렇게 안하고 걍 하나만 써
    longitude,
  };
  saveCoords(coordsObj);
  getWeather(latitude, longitude);
}

function handleGeoError() {
  console.log("Cant access geo location");
}

function askForCoords() {
  // 좌표를 요청하는 함수 만들기
  navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoError);
  //navigator api 사용. geolocation은 객체인데, 2개가 필요. 하나는 좌표를 가져오는 데 성공 시 처리하는 함수, 하나는 에러 뜰때?
}

function loadCoords() {
  const loadedCoords = localStorage.getItem(COORDS);
  if (loadedCoords === null) {
    askForCoords();
  } else {
    const parsedCoords = JSON.parse(loadedCoords);
    getWeather(parsedCoords.latitude, parsedCoords.longitude);
    // LS에 아무것도 없으면 getweather 함수 실행, 왜냐면 LS에 없으면 askForCoords 함수가 실행되고,
    // 이 함수 안에서 정상적으로 위치정보를 가져오면 handleGeoSuccess가 실행되는데, 이 안에서 API가 최종적으로 호출되기 떄문에
  }
  //get weather
}

function init() {
  loadCoords();
}

init();

 

const weather = document.querySelector(".js-weather");

const API_KEY = "8be8b30d5f392f273692fd1514c235b1"; // 날씨 api에서 가지고 온 것

// ++ API(appication programming interface; 다른 서버로부터 손쉽게 데이터를 가져올 수 있는 수단. 컴퓨터(machine)끼리 소통하기 위해 고안)

// 그래서 디자인 필요 없음. 걍 데이터만.

function getWeather(lat, lng) {

fetch(

`http://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}`;

});

// fetch()안에 가져올 데이터를 넣어주면 됌.

// 넣을 때도 ``활용해서 ${lat}, ${lng}, ${API_KEY} 넣어주고, 온도를 celsius로 표현하려고 마지막에 &units=metric 추가.

// then: 함수를 호출하긴 하지만, 데이터가 완전히 들어온 다음에 호출하는 것.

}

//js는 웹사이트로 request를 보내고 응답을 통해서 데이터를 얻을 수 있는데, 가져온 데이터를 refresh없이 나의 웹사이트에 적용가능하기 때문.

// 그래서 메일 확인할 때 새로고침 안해도 새로운 거 볼 수 있음. js가 뒤에서 계속 정보를 가져오기 떄문에.

// &appid=${API_KEY}를 입력해야 요청자의 api에 엄청 빡세게 요청하지는 않았음을 알 수 있음.

// js 코스 들으래.. 응,, 미친 then,,, 이해 안가.^^

const COORDS = "coords";

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, // 변수의 이름과 객체의 key를 같게 할 때는 latitude: latitude 이렇게 안하고 걍 하나만 써

longitude,

};

saveCoords(coordsObj);

getWeather(latitude, longitude);

}

function handleGeoError() {

console.log("Cant access geo location");

}

function askForCoords() {

// 좌표를 요청하는 함수 만들기

navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoError);

//navigator api 사용. geolocation은 객체인데, 2개가 필요. 하나는 좌표를 가져오는 데 성공 시 처리하는 함수, 하나는 에러 뜰때?

}

function loadCoords() {

const loadedCoords = localStorage.getItem(COORDS);

if (loadedCoords === null) {

askForCoords();

} else {

const parsedCoords = JSON.parse(loadedCoords);

getWeather(parsedCoords.latitude, parsedCoords.longitude);

// LS에 아무것도 없으면 getweather 함수 실행, 왜냐면 LS에 없으면 askForCoords 함수가 실행되고,

// 이 함수 안에서 정상적으로 위치정보를 가져오면 handleGeoSuccess가 실행되는데, 이 안에서 API가 최종적으로 호출되기 떄문에

}

//get weather

}

function init() {

loadCoords();

}

init();


++ 날씨 API 사이트

솔직히... 걍 이해 없이,,

예전에 r로 통계할 때 짜집기했던 것처럼 한 듯.. omg.. 진짜 이해 안가..

그때처럼 해도 되면 걍 구현 결과만 됐다고

생각하면 되겠으나..

로직을 알아야 하자나.. 😂

나아지겠지...

728x90
반응형