노마드코더 바닐라 JS로 크롬 앱 만들기 API사용

충찌·2022년 1월 9일
0

NomadCoders.chrome

목록 보기
7/7
post-thumbnail

드디어 마지막 강의!API를 사용해서 현재 위치, 날씨 등의 정보를 가져왔다.

그럴 때 navigator.geolocation.getCurrentPosition();을 사용한다.
-> wifi, gps, location 등에 대한 정보를 가져올 수 있다.
-> getCurrentPosition()은 2개의 argument를 필요로 함(성공했을 때 실행될 함수, 에러가 발생했을 때 실행될 함수)

에러가 발생할 경우 위치에 대한 정보를 가져올 수 없다고 알림창을 띄운다.
성공했을 경우 console.log(position);를 통해 많은 정보를 볼 수 있는데 우리는 경도와 위도를 사용한다.

위도와 경도에 대해 선언해주고
https://openweathermap.org에서 사용하려는 url을 복사해서 그곳에 위도와 경도 값을 넣어준다. appid는 개인정보에 적혀있다.

해당 url에 대한 정보는 아래와 같다. 날씨, 온도 나의 위치 등 다양한 정보를 얻을 수 있다.

{
  "coord": {
    "lon": 127.1589,
    "lat": 37.2844
  },
  "weather": [
    {
      "id": 721,
      "main": "Haze",
      "description": "haze",
      "icon": "50n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": -4.02,
    "feels_like": -4.02,
    "temp_min": -4.65,
    "temp_max": -1.67,
    "pressure": 1023,
    "humidity": 86
  },
  "visibility": 3200,
  "wind": {
    "speed": 0,
    "deg": 0
  },
  "clouds": {
    "all": 20
  },
  "dt": 1641734353,
  "sys": {
    "type": 1,
    "id": 5509,
    "country": "KR",
    "sunrise": 1641681935,
    "sunset": 1641717032
  },
  "timezone": 32400,
  "id": 6573747,
  "name": "Dongjinwon",
  "cod": 200
}

이제 url을 javascript에서 부르기 위해서 fetch()함수를 사용한다. 하지만 서버의 응답을 오래 기다릴 순 없으니 then()함수를 사용해준다. 이 부분은 다른 강의에서 더 깊게 설명해주니 일단 이런게 있구나~ 하고 넘겼다.
날씨와 도시, 온도에 대한 정보를 받아서 index.html에 값을 넣어주는 작업을 했다.
그 코드와 결과는 아래와 같다!

const API_KEY = "";


function onGeoOk(position){
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    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}`;
    });
}
function onGeoError(){
    alert("can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

따란~ 저 동네는 내가 사는 동네가 아닌데 일단 뜬다...왜지?ㅋㅋㅋ어쨌든!
이렇게 강의를 완료했다. 하지만 이건 예습이었을 뿐인게 내일부터 챌린지가 시작된다. 챌린지를 하면서 지금 사용한 것들을 복습도 하고
페이지도 더 멋지게 꾸며봐야겠다. 꾸미는게 제일 자신없는 부분이지만 그래도 노력은 해야지..

니코쌤 넘나 자세하고 친절하셔서 좋았고 나중에 기회가 되면 다른 강의도 (유료) 들어보고 싶다.
그럼 내일 챌린지를 위해 빠잉!

profile
벨로그? 난 켈로그

0개의 댓글