WEATHER

장돌뱅이 ·2022년 1월 27일
0

사용자의 geolocation(위치)를 주고 날씨를 보여준다.

  • step 1.
    navigator.geolocation.getCurrentPosition()
    이 함수를 부르면 브라우저에서 위치 좌표를 준다. 위도, 경도, 고도, 장치의 이동방향, 장치의 현재속도, gps, 와이파이 등
    - getCurrentPosition()는 2개의 인자가 필요하다. (** 참고: 사용자의 위치 변화 발생시 호출되는 함수는 watchPosition())
    하나는 모든게 잘 됐을 때 실행 될 함수(GeolocationPosition 객체를 유일한 매개변수로 받는 콜백 함수), 나머지 하나는 에러가 발생했을 때 실행될 함수(GeolocationPositionError (en-US) 객체를 유일한 매개변수로 받는 콜백 함수)다.
    - 위치를 허용할 경우 GeolocationPosition 객체에서 위도와 경도 정보를 얻는다.
  • step 2.
    - 위도와 경도를 장소로 바꿔주는 API 서비스를 사용한다. 사용자 위치에 대한 정보를 제공하는 url을 불러온다.
    - openweathermap.org 가입 후 API로 이동. 'current weather data' 이동. 현재 장치 위치의 날씨 정보를 알려줌
    - js 에서 url을 얻는 방법 : fetch(url)를 이용한다. 크롬의 Network로 이동하면 js가 url을 호출한 것을 볼 수 있다. 해당 url에서 사용자의 위치, 기온 등 json 형태의 데이터를 얻을 수 있다. fetch를 통해 해당 데이터 값을 가져와 사용한다.
    - url 뒤에 측정 unit을 &units=metric 으로 붙여 섭씨온도를 반환한다.
    - fetch() : promise. 뭔가가 당장 일어나지 않고 좀 뒤에 일어나는 것. 서버의 응답을 기다린다. 그래서 then을 사용한다.
    **API : 컴퓨터의 키보드 같이 '프로그램 간의 통신을 이뤄주는 것'이다.
    API를 호출함으로써 다른 프로그램에 어떤처리를 시켜 그 결과를 얻어올 수 있고 그를 이용할 수 있게 된다. API를 통해 다른 프로그램과 교류하게 되는 것이다.
const API_KEY = "1545879515889df25c23857021328cf1";

function onGeoOK(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  console.log("You live in", lat, lon);
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      const weather = document.querySelector("#weather span:first-child");
      const city = document.querySelector("#weather span:last-child");
      city.innerText = data.name;
      weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
    }); //js가 url 부름, promise(시간이 좀 걸린 뒤에 일어나는 것)
}

function onGeoError() {
  alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOK, onGeoError);

0개의 댓글