JavaScript_크롬 앱 만들기

서은서·2023년 3월 20일
0
post-thumbnail

5. Weather

1) 위치 자표 얻어오기

navigator.geolocation.getcurrentPosition(성공했을 때 함수, 실패했을 때 함수);

// 성공했을 때 함수
function onGeoOk(position){
	const lat = position.coords.latitude;
    const lon = position.coords.longitude;
}

// 실패했을 때 함수
funciton onGeoError(){
	console.log("We can't upload your location");
}

lat, log을 장소로 바꿔야 함 -> API가 필요함 -> openweathermap.org에서 얻을 수 있음

2) API

openweathermap.org에서 current weather Data를 통해 얻을 수 있음

// index.html

<div id="weather">
	<span></span>		// 날씨 & 온도(weather)
    <span></span>		// 지역(city)
</div>

// weather.js

const API_KEY="05f0fc3a71f9f30cedf96f9634f02d5c"; // sign up 후 얻을 수 있음

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`;
    // &units=metric : 섭씨온도로 바꿔줌
    fetch(url).then(response => reponse.json()).then(
    data =>{
    	const weather = document.querySelector("#weather span:first-child");
        const city = document.querySelector("#weather span:last-child");
        weather.innerText = `${data.weather[0].main} / ${data.main.temp}도`;
        city.innerText = data.name;
    }
    )
}
profile
내일의 나는 오늘보다 더 나아지기를 :D

0개의 댓글