본문 바로가기
개발공부/JavaScript

[바닐라 js로 크롬 앱만들기] 인강정리 (#8)

by dokii 2022. 4. 7.
728x90

목차

  1. 내 위치를 찍어보자 navigator.geolocation.getCurrentPosition(); 
  2. api로 날씨정보를 가져와보기
  3. 2번을 이용하여 원하는 데이터를 추출해보기

1.좌표를 찍어보자

navigator.geolocation.getCurrentPosition(); : 두개의 2개의 아규먼트가 필요함. 하나는 정상적으로 실행했을때의 함수, 하나는 실패했을때의 함수. 

html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <h2 id="clock">00:00</h2>
	  <form id="login-form"  class="hidden">
      
     <input required maxlength="15" type="text" placeholder="What is your name?" /> 
       <!--<button> Log in </button> -->
      <!--버튼대신 아래의 input으로 같은효과를--> 
      <input type="submit" value="Logggggg in" /> 
    </form>
    <!--
    <h2 id="clock">00:00</h2>
    -->
    <h1 class="hidden" id="greeting"></h1>
  
  
    
    

    <form id="todo-form">
      <input type="text" placeholder="write a To Do and Press Enter" required>
    </form>
    <ul id="todo-list"></ul>
      <!--<li>
        <span>text</span>
        <button>X</button>
      </li>-->
    <div id="food">
      <span>  </span>
      <span>  </span>
    </div>
    <script src="grettings.js"></script>
    <script src="clock.js"></script>
    <script src="foods.js"></script>
    <script src="todo.js"></script>
    <script src="weather.js"></script> <!----추가-->
  </body>
</html>

weather.js

function onGeoOk(position) {
    const lat = position.coords.latitude;
  const lng = position.coords.longitude;
  console.log("You live in", lat, lng);
  console.log(position);
}
function onGeoError() {
  alert("Can't find you. No weather for you.")
}

navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);

 

2. https://openweathermap.org/api 로들어가서 회원가입. 각종 날씨에 관련된 api를 사용할수 있음.

https://api.openweathermap.org/data/2.5/weather?lat=37.5444429&lon=127.0505535&appid=23a052c95564181b23ed71961347c101&units=metric 

로 호출하면 다음과 같은 데이터를 얻어온다. 

 

3. 위의 데이터를 확인후 필요한것을 불러옴

- fetch(url)로 url을 부를수있다.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <h2 id="clock">00:00</h2>
	  <form id="login-form"  class="hidden">
      
     <input required maxlength="15" type="text" placeholder="What is your name?" /> 
       <!--<button> Log in </button> -->
      <!--버튼대신 아래의 input으로 같은효과를--> 
      <input type="submit" value="Logggggg in" /> 
    </form>
    <!--
    <h2 id="clock">00:00</h2>
    -->
    <h1 class="hidden" id="greeting"></h1>
  

    <form id="todo-form">
      <input type="text" placeholder="write a To Do and Press Enter" required>
    </form>
    <ul id="todo-list"></ul>
      <!--<li>
        <span>text</span>
        <button>X</button>
      </li>-->
    <div id="food">
      <span>  </span>
      <span>  </span>
    </div>
    <div id="weather"> <!--추가-->
      <span>  </span>
      <span>  </span>
    </div>				<!--추가끝-->
    <script src="grettings.js"></script>
    <script src="clock.js"></script>
    <script src="foods.js"></script>
    <script src="todo.js"></script>
    <script src="weather.js"></script>
  </body>
</html>

weather.js

const API_KEY= "23a052c95564181b23ed71961347c101";

function onGeoOk(position) {
    const lat = position.coords.latitude;
  const lng = position.coords.longitude;
  console.log("You live in", lat, lng);
  //console.log(position);
  const url=`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`;
  console.log(url);
  fetch(url)
    .then(response => response.json())
    .then(data => { 
      const weather = document.querySelector("#weather span:first-child"); //--추가
      const city = document.querySelector("#weather span:last-child");//--추가
      //const name = data.name;
      //const weather = data.weather[0].main;
    
      city.innerText = data.name; //--추가
      weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;//--추가
      console.log(data.name, data.weather[0].main);//--추가
  });
}
function onGeoError() {
  alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);

https://codepen.io/okii_dokii_

 

4. 최종코드

 

'

https://replit.com/@okiidokii

728x90

댓글