크롬앱 #8 WEATHER

^^* ,,·2022년 4월 6일
0

8 WEATHER

1 API 사용

https://openweathermap.org/

2 Navigator

  • 사용자 에이전트의 상태와 신원 정보를 나타내며, 스크립트로 해당 정보를 질의할 때와 애플리케이션을 특정 활동에 등록할 때 사용

geolocation

  • 사용자의 현재 위치를 가져오는 API
  • navigator.geolocation.getCurrentPosition(성공,실패);

3 fetch()

: 네트워크에서 JSON 파일을 가져와서 콘솔에 출력함

https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fet

  • fetch 사용 요청방법
fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));

🔸 html

 	<div id="weather">
      <span></span> <!-- 도시자리 -->
      <span></span> <!-- 닐씨 자리 -->
    </div>

🔸 js

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

const API_KEY = "638932b0d124e5b26e3abba29abac448";

function onGeoOk(info) {
  const lat = info.coords.latitude;
  const lon = info.coords.longitude;
  const part = info.coords.part;
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;

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

  console.log(url);
  //console.log(url_2);

  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      city.innerText = `${data.name}\n`;
      weather.innerText = `${data.weather[0].main} / ${data.main.temp}'`;
    });
}

function onGeoErr() {
  alert("위치를 찾을 수 없습니다. ");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoErr);


0개의 댓글