<div id="weather">
<span></span>
<span></span>
</div>
const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
const API_KEY = "9c6f7d38dab7cf11abb520e1e3fb04ec";
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()) // 리스폰을 json 형태로 받고
.then((data) => { // json으로 받은 자료중 date를 이용 날씨를 불러온다.
city.innerText = data.name;
weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
});
}
function onGeoError() { //에러가 발생시 경고 문구가 나오게 하는 함수
alert("Can't find you. No weather for you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError)
navigator.geolocation 는 getCurrentPosition() 메소드를 이용하면 사용자의 위치에 대한 위도와 경도값을 얻을 수 있습
https://openweathermap.org/api 날씨 api를 얻을 수 있는 사이트(Current Weather Data를 사용)
- 회원가입 후 API키를 얻을 수 있다.
- url을 통해 경도 위도 입력 후 해당지역 날씨를 불러올 수 있다.
fetch()은 이용하면 Request나 Response와 같은 HTTP의 파이프라인을 구성하는 요소를 조작하는것이 가능