21.11.10 - TIL

jinny·2021년 11월 10일
0

TIL

목록 보기
8/32
post-thumbnail

FE팀 미니 프로젝트

현재 위치, 위치의 날씨 구하기

날씨 오픈 api를 이용해 날씨 정보 구하기

전체 코드

const weatherTemperate = document.querySelector('.temperate');
let temp_max; // 최고온도
let temp_min; // 최저 온도
let weather; // 현재 기상 상태

init();

function init() {
  positionWeather();
}

// 현재 위치의 날씨 정보를 가져오는 함수
function positionWeather() {
  const location = JSON.parse(localStorage.getItem('location'));

  if (location === null) getCoords();
  else getWeather(location.latitude, location.longitude);
}

// 현재 위치를 가져오는 함수
function getCoords() {
  navigator.geolocation.getCurrentPosition(successGeo, errorGeo);
}

// 현재 위치를 성공적으로 가져왔을 때 실행되는 함수
function successGeo(position) {
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;

  const coordsObj = {
    latitude,
    longitude,
  };
  localStorage.setItem('location', JSON.stringify(coordsObj));
}

// 현재 위치를 가져오지 못했을 때 실행되는 함수
function errorGeo() {
  console.log('Location is not correct');
}

// Open Weather API를 가져오는 함수
function getWeather(lat, lon) {
  fetch(
    `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid={자신만의 api}&units=metric`,
  )
    .then(response => {
      return response.json();
    })
    .then(json => {
      console.log(json);
      temp_max = Math.floor(json.main.temp_max);
      temp_min = Math.floor(json.main.temp_min);
      weather = json.weather[0].main;
      weatherInfo();
      weatherTemperate.innerHTML = `${temp_min}° ~ ${temp_max}°`;
    });
}

회고

함수로 만드는 연습을 해야할 것 같다! 처음엔 지저분하게 여기저기 다 썼는데 필요한 기능을 모아서 함수로 만드니깐 기능들이 한 눈에 보인다. 어제 콜백함수로 사용했을 때의 문제점을 발견하고 해결했는데 일반 함수로 만들어서 쓰는 것도 해결 방법 중 하나인 듯 싶다!

마무리 회고

오늘 마음이 싱숭생숭해서 많은 것을 하지 못했다.
내가 하고 있는게 맞는 길인지도 모르겠고 .. 해야할게 많은데 이것 저것 들쑤시는게 아닌가라는 생각도 든다. 공부 방향에 대해 다시 한번 진지하게 생각해야겠다.

profile
주니어 개발자의 기록

1개의 댓글

comment-user-thumbnail
2021년 11월 11일

함수의 기능말고 구성까지 생각하시는게 대단하신거 같아요 !

답글 달기