사용자의 위치 정보를 알아올 수 있는 함수
navigator.geolocation.getCurrentPosition()
두 가지 인자를 받는데 첫번째는 위치 불러오는 것이 성공했을 때 실행될 함수와 실패했을 때의 함수임.
JS (HTML 파일에 알아서 jS랑 연결)
function onGeoOk(position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
console.log("You live in",lat,lng);
}
function onGeoError() {
alert("can't find you. No weather for you");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
API 는 해당사이트에 들어가서 회원 가입해서 가져옴
https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
이게 API를 불러오는 url임
여기에 내 위도와 경도를 넣어주고 API 키를 넣어주면 되는 것임.
HTML (div를 새로 하나 만듬)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<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</h2>
<form class="hidden" id="login-form">
<input maxlength ="15" type="text" placeholder="What is your name?" required />
<button>Log In</button>
</form>
<h1 id="greeting" class="hidden"></h1>
<form id ="todo-form">
<input type ="text" placeholder="Write a Todo 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/greetings.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>
JS
const API_KEY = "f305813ac25efb6032d1ab6c80f3dcf0"
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())
.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} / ${data.main.temp}`;
});
}
function onGeoError() {
alert("can't find you. No weather for you");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);