티스토리 뷰

weather API를 사용해볼것이다.

https://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 the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

API KEY를 받기위해 회원가입한다.

API 문서를 잘 찾아보면 

이게 적당할 것 같다.

API는 그러면 어떻게 부르느냐? 이렇게 한다고 한다.

lat은 위도, lon은 경도일것임

이 정보는

navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);

이걸 이용해서 javascript에서 현재 위치의 정보를 가져올 수 있다.

성공 시, onGeoSuccess에 파라미터 하나를 넣어서 함수를 실행시킨다.

function onGeoSuccess(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
    });
}
function onGeoError() {
  alert("Can't find your location.");
}

이렇게 경도, 위도 값을 받을 수 있다. 그러면 API call에서 요구하는 값을 모두 얻었다!

  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric&lang=kr`;

주어진 api url을 백틱으로 저장하고 변수를 다 넣어준다.

참고로 해당 url을 열면

이런 JSON file이 열리게 된다.

이제 해야할 건,

 

1) 해당 페이지를 네트워크 연결 요청

2) 저 데이터를 string에서 JSON으로 가공

3) 원하는 key의 value를 가져옴

이다.

 

1)

바닐라 자바스크립트에서는 fetch()를 사용한다.

fetch(url)은 네트워크에서 url에 해당하는 JSON file을 가져온다.

2) 

fetch(url).then((response) => response.json())

가져오게 되면 then을 통해 이후 함수를 실행하게 되는데, 이때 반환하는 값은 HTTP 응답 전체를 나타내는 오브젝트이다.

여기서 json file만 쏙 빼오는 방법은, 저 반환값에 json()을 처리해주면 JSON FILE 본문을 반환하게 된다.

3)

fetch(url).then((response) => response.json()).then((data) => console.log(data));

이후 가공된 data를 입맛에 맞게 끌어오고 변수에 저장하고.. 뭐 그러면 되는 것이다. 

 

예를들어 내가 사는 곳의 온도를 가져오고 싶다고 해보자!

개발자 도구의 네트워크 - 미리보기에서 해당 url의 json file을 손쉽게 확인할 수 있다.

나는 저 description을 가져와 보고 싶다!

  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      console.log(data.weather[0].description);
    });

이후 확인해보면

잘 끌어오는 걸 확인할 수 있었다.

이후 변수를 지정해 원하는 값을 저장하고 입맛대로 사용하면 끝이다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함