[Vanilla JS] Momentum 크롬 앱 기능 만들기 - 3. 기타 기능 구현
시계 기능 구현하기
시계 기능을 구현하기 위해서는 먼저 Date() 객체로부터 현재 시간을 받아와야 한다.
Date - JavaScript | MDN (mozilla.org)
Date - JavaScript | MDN
JavaScript Date 객체는 시간의 한 점을 플랫폼에 종속되지 않는 형태로 나타냅니다. Date 객체는 1970년 1월 1일 UTC(협정 세계시) 자정과의 시간 차이를 밀리초로 나타내는 정수 값을 담습니다.
developer.mozilla.org
그 다음 setInterval()함수를 이용해 매 초마다 새롭게 시간을 갱신시켜주면 시계 기능이 구현된다.
다만 여기서 주의할 점은, .getSeconds() 등으로 받아온 시간 정보는 number 형식이므로, 만약 1초대의 시간이 되면
13:24:05 의 형식이 아니라 13:24:5 와 같이 균형이 깨지게 된다.
따라서 String().padStart() 함수를 이용해 나머지 글자수를 채워주어야 한다.
String.prototype.padStart() - JavaScript | MDN (mozilla.org)
String.prototype.padStart() - JavaScript | MDN
padStart() 메서드는 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 시작(좌측)부터 적용됩니다.
developer.mozilla.org
기존문자열.padStart(문자열 길이, 추가할 문자열)
padStart는 기존 문자열 앞에 추가할 문자열을 추가하고
padEnd는 반대로 기존 문자열 뒤에 추가한다.
배경 이미지 랜덤화 하기
배경 이미지는 따로 img폴더에 번호순으로 저장해둔 뒤, random 함수를 이용해 가져온다.
여기서 Math.random()은 0이상 1미만의 소수를 반환하는데, 거기에 배열의 개수를 곱한 뒤 나머지 소수점을 버려주면
랜덤하게 값을 선택할 수 있게 된다.
날씨 정보 가져오기
날씨정보는 현재 내 위치정보를 바탕으로 API를 통해 제공받을 수 있다.
Geolocation API 사용하기 - Web API | MDN (mozilla.org)
Geolocation API 사용하기 - Web API | MDN
Geolocation API는 navigator.geolocation 객체를 통해 사용할 수 있습니다.
developer.mozilla.org
navigator 객체에는 geolocation 속성이 있으며 이 속성에는 현재 위치정보를 가져오는 메소드가 존재한다.
navigator.geolocation.getCurrentPosition(성공함수, 실패함수)
객체정보를 가져오는 데 성공하면 첫번째 콜백함수가, 실패하면 두번째 콜백함수가 실행된다.
성공했을 때의 객체 정보를 표시해보자면 다음과 같다.
여기서 우리가 필요한 것은 latitude 와 longitude 속성이다.
Current weather data - OpenWeatherMap
Current weather data - OpenWeatherMap
Access current weather data for any location on Earth including over 200,000 cities! We collect and process weather data from different sources such as global and local weather models, satellites, radars and a vast network of weather stations. Data is avai
openweathermap.org
위의 페이지를 살펴보면 다음과 같은 url을 통해 날씨 정보를 가져올 수 있게 된다.
https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
위의 변수부분에 추출해낸 위도와 경도 정보를 입력한 뒤 fetch(url)명령을 통해 정보를 받아온다.
정보를 받아오고 이를 .json() 메소드로 변환하면 우리가 원하는 정보를 얻을 수 있다.
비록 API_KEY를 하드코딩 하긴 했지만, 보안 부분은 일단 제쳐두자.
결과
<!DOCTYPE html>
<html lang="ko">
<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//main.css"/>
<script defer src="./javascript/greeting.js"></script>
<script defer src="./javascript/todo.js"></script>
<script defer src="./javascript/misc.js"></script>
<title>Momentum practice</title>
</head>
<body>
<div id="greeting">
<form id="login">
<div>Hello, what's your name?</div>
<input type="text" placeholder="이름" />
</form>
<div id="todo" class="hidden">
<div id="clock">00:00:00</div>
<div id="weather">
<span></span>
<span></span>
</div>
<div id="hello"></div>
<form>
<input type="text" placeholder="할 일" />
</form>
<ul></ul>
</div>
</div>
<img id="background" src="./img/1.jpeg" alt="배경"/>
</body>
</html>
// background Image
const backgroundEl = document.querySelector("#background");
const url = `./img/${Math.floor(Math.random() * 3)}.jpeg`;
backgroundEl.src = url;
// clock
const clockEl = document.querySelector("#clock");
const now = new Date();
setInterval(() => {
const now = new Date();
const hour = String(now.getHours()).padStart(2, "0");
const minute = String(now.getMinutes()).padStart(2, "0");
const second = String(now.getSeconds()).padStart(2, "0");
time = `${hour}:${minute}:${second}`;
clockEl.innerText = time;
}, 1000);
// weather
const weatherEl = document.querySelector("#weather");
const cityEl = weatherEl.querySelector(":first-child");
const wthEl = weatherEl.querySelector(":last-child");
function successPosition(pos) {
const lat = pos.coords.latitude;
const lon = pos.coords.longitude;
const API_KEY = "48a7d2a5e745987942ee2c85e9946274";
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 city = data.name;
const weather = data.weather[0].main;
const temp = data.main.temp;
cityEl.innerText = city;
wthEl.innerText = `${weather}, ${temp}`;
});
}
function errorPosition(error) {
console.log(error);
}
navigator.geolocation.getCurrentPosition(successPosition, errorPosition)