초보 개발자의 성장 일기

[JavaScript] 내 위치로 날씨 불러오는 방법 본문

Development/JavaScript

[JavaScript] 내 위치로 날씨 불러오는 방법

YUNA 2024. 3. 5. 01:12

위치 허용을 하게 되면 내 위치의 위도와 경도를 불러오는 자바스크립트 내장 함수가 존재한다.

 

navigator.geolocation.getCurrentPosition()

2개의 콜백함수를 인자를 받는데 첫번째는 위치를 성공적으로 불러왔을 때, 두번째는 실패했을 때 실행시킬 각각의 함수를 불러온다.

 

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

위치를 불러왔을 때 위도, 경도를 상수로 저장하고, 실패했을 때 함수를 각각 만들어서 getCurrentPosition안에 넣어준다.

 

 

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

OpenWeather Weather forecasts, nowcasts and history in a fast and elegant way

openweathermap.org

날씨 API를 불러오는 페이지이다.

회원가입 후 로그인하고 상단 메뉴에서 API로 들어간다.

 

사용할 API

그 중 이 API를 사용한다.

API문서를 클릭하면 위치에 대한 현재 날씨를 알 수 있다.

 

우선 내 API key를 알아야 한다.

내 API key

계정을 누르면 My API keys가 있다.

 

이 key가 있어야 API 사용이 가능하다.

 

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}

{lat}, {lon}, {API key}에 위도, 경도, 내 API key를 넣으면 위도 경도에 맞는 날씨가 나온다.

 

const API_KEY = ''

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

url을 넣어주고 fetch하면 날씨 데이터를 불러올 수 있다.

네트워크 탭을 열어 확인하면 날씨관련 다양한 데이터가 넘어오는 것을 확인할 수 있다.

 

 

units을 사용하려면 주소의 마지막에 붙여주면 된다.

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) => {
      console.log(data.name, data.weather[0].main);
    });

fetch로 전체 불러오는 데이터 확인 후 원하는 데이터만 가져오면 된다.