노마드코더 바닐라JS 8강

이안이다·2023년 5월 28일
0

JavaScript

목록 보기
6/6
post-thumbnail

지난 7강까지 todo.js를 구현했고 이번 8강부터는 weather.js파일을 구현한다.

navigator.geolocation.getCurrentPosition();

navigator라는 함수와 내부 두 가지 모듈이다. 이걸 그냥 부르기만 하면 브라우저가 위치 좌표를 준다. 매우 유용한 기능이다.

getCurrentPosition()은 두 개의 인자가 필요하다.
하나는 정상시 실행할 함수, 둘은 오류시 실행할 함수다.

그래서 아래와 같은 코드를 작성할 수 있다.

function onGeoOk(position) {
  const lat = position.coords.latitude; //위도
  const lon = position.coords.longitude; //경도
  console.log("당신의 위치는 : ", lat, lng);
}
function onGeoError() {
  alert("못 찾겠다 꾀꼬리");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

굳이 설명 안 적어도 코드만 봐도 충분히 이해할 수 있는 난이도다.

코드를 실행하면 이렇게 위치 정보 제공을 허용하겠냐는 alert가 뜨고 동의를 하면 console에서 다음과 같이 위치 정보를 확인할 수 있다.


근데 맘에 안 든다. 저 숫자 가지고 내가 뭘 어떻게 알아. 그래서 저 위도와 경도를 이쁘게 사용하기 위해 API를 사용해야한다.



openweather.org를 검색하고 들어가면 이런 사이트가 나온다. 별별게 다있네. 여기서부터 API를 사용할건데 API에 대한 공부는 어느정도 해봤으니까 설명은 패스. 어쨌든 기본적으로 API는 다른 서버들과 이야기할 수 있게 해주는 방법임 !


요녀석을 사용할거다. 이 주소를 그대로 긁어서 {lat}자리에 위도, {lon}자리에 경도, 그리고 키 자리에 키를 입력해주면!!??!

짜잔~ 개같은 에러가 뜬다.
왜냐하면 계정 인증을 하지 않았기 때문 !! 니꼴라스는 이정도는 강의에서 알려줘야지 ㅡㅡ 에러코드 401인 거 보고 알아챘다.


Error code : 401

HTTP(하이퍼텍스트 전송 프로토콜) 401 Unauthorized 응답 상태 코드는 요청된 리소스에 대한 유효한 인증 자격 증명이 없기 때문에 클라이언트 요청이 완료되지 않았음을 나타낸다. 코딩을 하다보면 자주 등장하는 에러들 중 하나니까 기억해두면 편하다 !


이메일로 계정 인증 끝내고 다시 시도하면

이런 코드들이 뜬다. 자세한 건 나중에 다시. 일단 맨 아래에 Gongju라고 나오는 걸 보면 세종시에서 작성 중인 현재 기준 맞는 것 같음.

url을 어떻게 불러오는지에 대해 배울 거다. 아래와 같이 내가 직접 위도와 경도, api키값을 입력했던 걸 사용자가 입력했던 거로 대체하게끔 코드를 수정해보자

const url = 
      "https://api.openweathermap.org/data/2.5/weather?lat=36.5003169&lon=127.2650979&appid=487576c034c1bb192f4ba7a0e54a50ba";

요거를 수정하면 아래와 같아진다.

const url =
    "https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}";

뭔가 이상하다 싶어서 헤맸더니 그레이브를 안 쓰고 큰따옴표를 쓰고 있었다. 나는 이런 멍청한 실수 안 할 줄 알았는데 언제나 예상보다 더 멍청한 나다.

const url =
    `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}`;

다시 수정 해주고 잘 되는지 확인을 위해 console.log를 찎고 나온 url을 타고 가보면 !?

콘솔에 찍힌 url !

잘 된다.



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

뒤에 이렇게 units=metric를 붙이면 화씨온도를 섭씨온도로 바꿀 수 있음.

const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
const API_KEY = "487576c034c1bb192f4ba7a0e54a50ba";

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) => {
      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);

최종적으로 이렇게 weather.js 파일을 완성할 수 있다.

근데 이렇게 못 생기게 프로젝트를 마무리 할 수는 없다.
이제부터 열심히 CSS를 꾸며보자 !!!

profile
경제와 개발을 곁들인 기획자..!

0개의 댓글