#TIL29

전혜린·2021년 9월 5일
0

Today I Learned

목록 보기
47/64

Geolocation API 사용하기

  • Geolocation API는 사용자의 현재 위치를 가져오는 API로, 지도에 사용자 위치를 표시하는 등 다양한 용도로 사용할 수 있음

현재 위치 가져오기

  • getCurrentPosition() 메소드를 호출해서 사용자의 현재 위치를 얻을 수 있음
  • getCurrentPosition()은 사용자의 위치를 탐지하는 비동기 요청을 초기화하고, 위치 관련 하드웨어에 최신 정보를 요청함
  • 위치를 알아낸 후에는 지정한 콜백 함수를 호출함 선택적으로, 이 과정 중 오류가 발생하면 호출할 오류 콜백을 두 번째 매개변수로 지정할 수도 있음
  • 문법) navigator.geolocation.getCurrentPosition(success, error)
  • success: 성공시 실행되는 콜백함수
  • error: 실패시 실행되는 콜백함수

Using Fetch

  • Fetch API를 이용하면 Request나 Response와 같은 HTTP의 파이프라인을 구성하는 요소를 조작하는것이 가능
  • 네트워크에서 리소스를 가져오는 프로세스를 시작하여 응답을 사용할 수 있게 되면 이행되는 약속을 반환
  • fetch()로 부터 반환되는 Promise 객체는 HTTP error에 대해 거부 하지 않으며 네트워크 오류에 대해서만 거부함

<예시>

<script>
  function success(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(function(data) {
      const temp = document.querySelector('.weather .temp');
      const condition = document.querySelector('.weather .condition');
      const city = document.querySelector('.weather .city');
      temp.textContent = `${Math.floor(data.main.temp)}º`;
      condition.textContent = data.weather[0].main;
      city.textContent = data.name;
    });
  };

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

  navigator.geolocation.getCurrentPosition(success, error);
</script>
profile
코딩쪼아

0개의 댓글