wheather API - openweathermap

Woohyun·2022년 10월 24일
0
post-thumbnail

준비 사항

openweathermap API
fetch
navigator.geolocation

openweathermap API

위치 정보를 기반하여 날씨 정보를 얻을 수 있다.

fetch

fetch 매서드는 JavaScript에서 서버로 네트워크 요청을 보내고 응답을 받을 수 있도록 해주는 매서드이다.
openweathermap API와 연결하여 응답을 받을 수 있도록 한다.

geolocation API는 사용자의 현재 위치 정보를 가져올 때 사용하는 자바스크립트 API이다.

사용자의 위도 및 경도에 관한 정보는 자바스크립트를 이용해 웹 서버로 전송되며 이것을 이용하면 사용자의 위치를 지도에 표시하거나, 사용자 근처의 상점을 찾아주는 등의 위치기반 서비스를 할 수 있다.

하지만 이러한 정보는 사용자의 사생활을 침해할 가능성이 높으므로, 사용자의 동의 없이는 사용할 수 없다.

사용자 동의 필요

날씨 정보를 가져와 html상에 표시해보자!

전체코드

const API_KEY = "YOUR_API_KEY"

function onGeoOK(location) {
	// location 정보를 인자값으로 받기
    const lat = location.coords.latitude;
    const lng = location.coords.longitude;
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}`;
    fetch(url) // fetch로 서버와 통신
    .then(respone => respone.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;
    });
}

function onGeoError () {
    alert("찾을 수가 없습니다.")
}

navigator.geolocation.getCurrentPosition(onGeoOK,onGeoError);

openweathermap API 적용 사진

openweathermap 공식 사이트
https://openweathermap.org/

geolocation API
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/geolocation

노마드코더 강의 참고
바닐라 JS로 크롬 앱 만들기

profile
개발자 지망생

0개의 댓글