[#63] 날씨 오픈 API 연동

2025. 4. 28. 16:25·LG 유플러스 유레카 SW/React
목차
  1. OpenWeatherMap(오픈 웨더 맵)
  2. 1️⃣ 로그인 및 API Key 발급
  3. 2️⃣ VSCode 확장 프로그램 thunder client로 API 테스트
  4. 3️⃣ 환경 변수 설정
  5. 4️⃣ API 연동 코드 작성
  6. 5️⃣ WeatherPage 컴포넌트 구현

OpenWeatherMap(오픈 웨더 맵)

https://openweathermap.org/

 

Current weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

 

1️⃣ 로그인 및 API Key 발급

 

2️⃣ VSCode 확장 프로그램 thunder client로 API 테스트

https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid={API_KEY}

 

3️⃣ 환경 변수 설정

  • 루트에 .env.local 파일 생성 및 .gitignore 등록
VITE_WEATHER_API_KEY=발급받은_키값
⚠️ Vite는 반드시 VITE_로 시작해야 환경 변수를 인식할 수 있음

 

4️⃣ API 연동 코드 작성

4-1. 기본 설정

  • Vite에서는 환경변수를 가져올 때 process.env가 아니라 import.meta.env 사용
import axios from 'axios'

const API_KEY = import.meta.env.VITE_WEATHER_API_KEY
const BASE_URL = 'https://api.openweathermap.org/data/2.5/weather'

4-2. 좌표로 날씨 정보 가져오기

export const getWeatherByCurrentLocation = async (lat, lon) => {
  try {
    const res = await axios.get(
      `${BASE_URL}?lat=${lat}&lon=${lon}&appid=${API_KEY}&lang=kr&units=metric`
    )
    return res.data
  } catch (err) {
    console.log('좌표로 날씨 정보 가져오기 실패: ', err)
  }
}

4-3. 현재 위치 기반으로 날씨 정보 가져오기

  • navigator.geolocation.getCurrentPosition API를 사용해 브라우저에서 사용자 위치를 요청
export const getCurrentData = async () => {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(
      async position => {
        try {
          const { latitude, longitude } = position.coords
          const res = await getWeatherByCurrentLocation(latitude, longitude)
          resolve(res)
        } catch (err) {
          console.log('좌표로 날씨 정보 가져오기 실패: ', err)
          reject(err)
        }
      },
      err => {
        console.log('위치 정보 가져오기 실패: ', err)
        reject(err)
      }
    )
  })
}

4-4. 도시명으로 날씨 정보 가져오기

export const getCountryData = async city => {
  try {
    const res = await axios.get(
      `${BASE_URL}?q=${city}&appid=${API_KEY}&lang=kr&units=metric`
    )
    return res.data
  } catch (err) {
    console.log('도시명으로 날씨 정보 가져오기 실패: ', err)
  }
}

 

5️⃣ WeatherPage 컴포넌트 구현

5-1. useSearchParams를 이용해 URL에 따른 날씨 데이터 보여주기

const [searchParams, setSearchParams] = useSearchParams()
const city = searchParams.get('city')
const [weatherData, setWeatherData] = useState(null)

useEffect(() => {
  const fetchWeatherData = async () => {
    try {
      let data
      if (city) {
        data = await getCountryData(city)
      } else {
        data = await getCurrentData()
      }
      setWeatherData(data)
    } catch (err) {
      console.log('날씨 데이터 가져오기 실패: ', err)
    }
  }
  fetchWeatherData()
}, [city])

5-2. 도시 변경 핸들러

const handleChangeCity = city => {
  city === 'current' ? setSearchParams({}) : setSearchParams({ city })
}

 

 

728x90
반응형

'LG 유플러스 유레카 SW > React' 카테고리의 다른 글

[#65] React + Express + MongoDB 연동하기 (feat. 회원가입)  (3) 2025.04.30
[#64] TanStack Query(React Query) 사용해보기  (0) 2025.04.29
[#62] 용돈 기입장 프로젝트 (feat. React)  (0) 2025.04.28
[#61] Redux란  (1) 2025.04.24
[#60] React - Hook + 성능 최적화 정리  (0) 2025.04.23
  1. OpenWeatherMap(오픈 웨더 맵)
  2. 1️⃣ 로그인 및 API Key 발급
  3. 2️⃣ VSCode 확장 프로그램 thunder client로 API 테스트
  4. 3️⃣ 환경 변수 설정
  5. 4️⃣ API 연동 코드 작성
  6. 5️⃣ WeatherPage 컴포넌트 구현
'LG 유플러스 유레카 SW/React' 카테고리의 다른 글
  • [#65] React + Express + MongoDB 연동하기 (feat. 회원가입)
  • [#64] TanStack Query(React Query) 사용해보기
  • [#62] 용돈 기입장 프로젝트 (feat. React)
  • [#61] Redux란
nueos
nueos
  • nueos
    nueos 공부 기록
    nueos
  • 전체
    오늘
    어제
    • 분류 전체보기 (191)
      • 해커톤 (1)
      • 네이버 BoostCamp (6)
      • LG 유플러스 유레카 SW (3)
        • React (21)
        • TypeScript (2)
        • JavaScript (2)
        • HTML+CSS (5)
        • Spring (7)
        • Java (6)
        • SQL (2)
        • Algorithm (8)
        • CX (6)
        • Git (2)
        • 프로젝트 (2)
        • 스터디 (9)
        • 과제 (8)
        • 특강 (1)
      • React (3)
      • Next (0)
      • Javascript (2)
      • HTML (2)
      • CSS (9)
      • Algorithm (6)
      • Database (0)
      • OS (13)
      • C++ (24)
      • Python (1)
      • jQuery (1)
      • Django (1)
      • Git (1)
      • 개발 지식 (3)
      • 정보 보안 (22)
      • 포렌식 (1)
      • 암호 (2)
      • 기타 (4)
      • 패스트캠퍼스 FE 프로젝트십 (5)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    완전 탐색
    힙
    exhaustive search
    제주해커톤
    스택
    큐
    Stack
    기술로바꾸는세상
    제주지역혁신플랫폼지능형서비스사업단
    heap
    Queue
    디지털혁신
    디지랩챌린지
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
nueos
[#63] 날씨 오픈 API 연동
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.