VanillaJS 4021

Sammy·2022년 4월 21일
0

arr.filter()
: filter는 기존 arr에는 영향을 주지않고 조건을 걸어서 값을 필터링할 수 있다. 예를 들면

const arr = [1,2,3,4,5];

const newArr = arr.filter(i => i > 2);
console.log(newArr); // [3,4,5]

API를 사용해서 위치와 날씨 표시하기

사이트: openweathermap.org

weather.js

function onGeoOk(position){
  const lat = position.coords.latitude;
  const lng = position.coords.longitude;
  console.log("You live it.", lat, lng)
}

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

navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);

단 10줄로 사용자의 위치와 날씨를 가져올 수 있다.

API와 결합하기

const API_KEY = "85ac0314bbec154c5875e077cb232e1a";

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}`;
  }); // js가 url호출해서 json에 있는 data 가져오기
}

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

navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);

이걸로 오늘 바닐라JS 강의를 수료했다.
21기 수강생분들 완성작을 봤는데 너무 퀄리티 있게 만드셔서 자극을 많이 받았다.
나도 이쁘게 꾸며서 꼭 성공해야겠따!

profile
Web Developer

0개의 댓글