navigator.geolocation.getCurrentPosition()
실행 시 브라우저가 위치 좌표(WiFi, 위치, GPS 등)를 주는 함수이다. 두가지 인자를 받는데, 하나는 success 함수이고 나머지 하나는 error 함수이다.
success 함수는 GeolocationPosition 객체 하나를 입력 받는다.
weather.js 최종 완성 코드
const API_KEY="";//본인 API KEY 입력
function onGeoOk(position){
const lat=position.coords.latitude;
const lon=position.coords.longitude;
//url의 위도와 경도, API를 받은 값 lat, lon, API_KEY로 대체해 줌
//API_KEY 자리에는 본인의 API KEY값을 넣으면 됨
//화씨 온도를 섭씨 온도로 바꾸기 위해 url 뒤에 &units=metric을 추가함
const url=`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`
//url 얻기
fetch(url)
.then((response)=>response.json())
.then((data)=>{
const weather=document.querySelector("#weather span:first-child")//span:하고 붙여쓰기. 띄어썼더니 오류남
const city=document.querySelector("#weather span:last-child")
city.innerText=data.name;
//weaher은 콘솔 창을 확인해 보면 배열이므로 첫번째 요소(weather[o])를 가져온 후 원하는 값인 main을 가져옴
//{날씨 / 온도 위치} 형식으로 출력
weather.innerText=`${data.weather[0].main} / ${data.main.temp}`;
});
}
function onGeoError(){
alert("Can't find you. No weater for you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);
최종 index.html 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css"/>
<title>Momentum App</title>
</head>
<body>
<h2 id="clock">00:00:00</h2>
<form class="hidden" id="login-form">
<input
required
maxlength="15"
type="text"
placeholder="What is your name?"
/>
<input type="submit" value="Log In"/>
</form>
<h1 id="greeting" class="hidden"></h1>
<form id="todo-form">
<input type="text" placeholder="Write a To Do and Press Enter" required/>
</form>
<ul id="todo-list"></ul>
<div id="quote">
<span></span>
<span></span>
</div>
<div id="weather">
<span></span>
<span></span>
</div>
<script src="js/greeting.js"></script>
<script src="js/clock.js"></script>
<script src="js/quotes.js"></script>
<script src="js/background.js"></script>
<script src="js/todo.js"></script>
<script src="js/weather.js"></script>
</body>
</html>
끝!