OpenWeatherMap(오픈 웨더 맵)
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. 회원가입) (2) | 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 |