Roxylife
Roxy 빛나는 새벽
Roxylife
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발(회고록)현황일기
    • 개발CS지식
    • 알고리즘문제풀기
    • Git
    • 개발언어
      • HTML, CSS
      • JavaScript
    • 프론트엔드
      • React
    • Side Project
      • 혼자Project
      • 팀Project
    • 교육참여
      • [스파르타코딩클럽]
      • [저스트코드]

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • JavaScript
  • 노마드코더
  • 회고록
  • JUSTCODE6기
  • git
  • 개발
  • 저스트코드
  • 기업협업
  • 저스트코드6기
  • 팀프로젝트
  • 바닐라JS크롬앱
  • 코딩교육
  • 힙한취미코딩이벤트
  • 스파르타코딩클럽후기
  • 스파르타코딩클럽
  • 드림코딩
  • JUSTCODE
  • 코코아톡클론
  • 신년운세코딩패키지
  • 스터디코드

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Roxylife

Roxy 빛나는 새벽

Weather날씨 만들기
개발언어/JavaScript

Weather날씨 만들기

2021. 9. 4. 12:47

navigator.geolocation.getCurrentPosition(success, error)

Step 1. 사용자의 위치를 알아본다. (현재 위치의 위도와 경도)

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

// 사용자의 현재 위치를 요청한다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

GeolocationPosition object 중에 coords.latitude (위도) / coords.longitude (경도)

function onGeoOk(position) {
  const lat = position.coords.latitude;
  const lon = 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);

콘솔창 결과

Step 2. 콘솔창에 있는 숫자들을 장소로 바꿔줄 서비스를 사용한다. 

▶ http://openweathermap.org > API 메뉴 클릭 > Current Weather Data > API docs 클릭

▶ By geographic coordinates API call 복사해서 새창에다 주소를 붙여넣기 한 뒤에

주소중에서 각각 {lat}, {lon}, {API key} 안에 콘솔창에 있던 숫자들을 넣고

API key 경우엔 나의 프로필 Api keys > key 를 넣는다.

나의 API

const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";

Step 3. JavaScript에서 url을 부르는 방법.

url을 설정한 뒤, 앞에서 숫자들을 ${lat}, ${lon}, ${API_KEY}로 백팁으로 감싸준다.

const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";

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}`;
  console.log(url);
}
function onGeoError() {
  alert("Can't find you. No weather for you.");
}

// 사용자의 현재 위치를 요청한다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

콘솔창 결과에 나온 url이 잘 실행하면 성공!!!!!

 

Step 4. fetch를 이용해서 URL 얻기

fetch(url); 해본다. ▶ 콘솔창 network창에 들어가 새로고침 clear버튼누르면, weather url정보를 얻을 수 있다.

const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";

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

fetch url을 이용한 NetWrok창 살펴보기

만약, url을 수정할 수가 있는 선택옵션(optional)이 있는데, 그건 units=metric을 추가해본다.

Parameter 매개변수

const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;

이것이 JSON!!!

const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";

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는 promise (당장 일어나지 않고 시간이 좀 걸린 뒤에 일어나는 현상)
  // URL을 fetch하고 response를 받아야 한다. 그리고 response의 json을 얻어야 한다.
  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      console.log(data.name, data.weather[0].main);
    });
}
function onGeoError() {
  alert("Can't find you. No weather for you.");
}

// 사용자의 현재 위치를 요청한다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

콘솔창 결과

<div id="weather">
      <span></span>
      <span></span>      
</div>
const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";

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는 promise (당장 일어나지 않고 시간이 좀 걸린 뒤에 일어나는 현상)
  // URL을 fetch하고 response를 받아야 한다. 그리고 response의 json을 얻어야 한다.
  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);

 

강의 끝!!! 

'개발언어 > JavaScript' 카테고리의 다른 글

[JavaScript] 변수가 필요한 이유와 선언하는 방법  (0) 2022.07.29
[JavaScript] 데이터 타입 Data Types 의 종류  (0) 2022.07.27
To Do List 만들기  (0) 2021.09.03
Quotes and Background 명언 만들기  (0) 2021.09.02
Clock만들기  (0) 2021.09.01
    '개발언어/JavaScript' 카테고리의 다른 글
    • [JavaScript] 변수가 필요한 이유와 선언하는 방법
    • [JavaScript] 데이터 타입 Data Types 의 종류
    • To Do List 만들기
    • Quotes and Background 명언 만들기
    Roxylife
    Roxylife
    꿈나무 FE개발자

    티스토리툴바