[JavaScript] 바닐라 JS로 크롬 앱 만들기_#12

강성일·2023년 3월 8일
0
post-thumbnail

Geolocation

첫 번째는 getCurrentPosition 사용하는 것이다.
getCurrentPosition은 인자를 두 개 받는다.
하나는 성공했을 때, 하나는 실패했을 때로 나눠진다.


function onGeoOk(position) {
  const lat = position.coords.latitude;
  const log = position.coords.longitude;
  console.log("You live it", lat, log);
}

function onGeoError() {
  alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

위치 파악에 성공했을 때 함수를 onGeoOk라고 정하였다.
console.log(position)을 찍어보면 GeoLocationPosition 이 뜨는데 그 안에
coords 를 눌러보면 현재 위치의 위도와 경도인 latitude, longitude 을 알 수 있다.


Weather API

두 번째는 위도와 경도를 장소로 바꿔줄 서비스를 사용하는 것이다.
근데 그 전에 먼저 API 계정을 열도록 하자.

Сurrent weather and forecast

우리가 사용할 것은 Current Weather Data 이다.

📄 오픈 소스 >

[https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid=](https://api.openweathermap.org/data/2.5/weather?lat=%7Blat%7D&lon=%7Blon%7D&appid=){API key}

사이트에서 받아온 링크에서 이전에 알아뒀던 위도와 경도, 그리고 내 API Keys를 넣어준다.
그럼 놀랍게도 내가 살고 있는 현재 위치의 날씨 정보와 온도 등등 많은 정보가 화면에 뜨게 된다.

다시 vscode로 돌아와 내 API를 담아둘 곳을 임의로 만들어둔다.

이제 우리는 URL을 불러올 것이다.


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}`;
  fetch(url);
}

function onGeoError() {
  alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

API 사이트에서 받아온 링크에 ${}로 사용자의 lat, lon, API 를 넣어서 백틱으로 묶어 url을 만들어준다.
console.log로 url을 넣은 후 콘솔창에서 보면 url이 정상적으로 뜬다.
누르면 브라우저가 url로 이동해서 응답을 얻는다.

하지만 우리는 fetch를 이용할 것이다.
fetch 로 url 을 묶어준 후 브라우저에서 inspect를 눌러보면 콘솔창에~?

아무것도 뜨지 않는다.
콘솔창이 아니라 network 창으로 가야한다 ㅋ.ㅋ

새로고침을 하고 allow를 누르면 weahter~ 라고 뜨는 것을 볼 수 있다.
이것은 브라우저가 아니라 JS가 URL을 대신 불러준 것이다.

fetch를 사용하면 우리가 URL로 직접 가지 않아도 된다는 뜻이다.
Preview 탭으로 가면 응답 결과를 아주 깔끔하게 볼 수 있다.
확인해본 결과 온도 값인 temp가 279.42 나 나왔다
화씨 온도라는 것을 짐작해볼 수 있었다.

따라서 Weather API 사이트를 참고하면 Unit을 보낼 수 있는데
이것을 이용하여 주소 값 뒤에 &units=metric 을 붙여준다.
그럼 온도 값 3.97 으로 제대로 나오는 것을 볼 수 있다.


const API_KEY = "";

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);

그다음 html에 id=weather 하나 만들어주고 span을 두 개 넣어준다.
그리고 JS로 돌아와 then 문법을 사용하여 다음과 같이 코딩하고 값들을 innerText로 나타내주면 홈페이지에 바로 현재 나의 날씨와 온도, 그리고 위치를 볼 수 있다.

20줄만으로 나의 위치를 계속 따올 수 있다는 것이 정말.. JS는 미친 것 같다.

아 참고로 API KEY 는 개인정보이므로 깃허브에 올릴 때. 주의해야한다.
따라서 아래 사이트를 참고하여 키 값을 간단하게 가려 깃허브에 올렸다 !

javascriptでapiキーを隠す方法



✅ 최종 코드

<!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</title>
  </head>
  <body>
    <form class="hidden" id="login-form">
      <input
        required
        maxlength="15"
        type="text"
        placeholder="what is your name?"
      />
      <input type="submit" value="Log in"></input>
    </form>
    <h2 id="clock">00:00:00</h2>
    <h1 id="greeting" class="hidden"> i'm hiding !</h1>
    <form id="todo-form">
      <input type="text" placeholder="Write a To Do and press the 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>
    <script type ="text/javascript" src="js/apikey.js"></script>
  </body>
</html>
function onGeoOk(position) {
  const API_KEY = apikey;
  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);
profile
아이디어가 넘치는 프론트엔드를 꿈꿉니다 🔥

0개의 댓글