[TIL]23.03.28 날씨API

dalCoding·2023년 3월 28일
0

Techit 블록체인 스쿨 3기 Today I Learned

날씨 API 사용하기
https://openweathermap.org/

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={APIkey}
lat: 위도
lon: 경도
APIkey: 발급받은 api키 입력

<body>
    <div>
        <div>
            <img class="weatherIcon" src="https://openweathermap.org/img/wn/10d@2x.png" alt="weather" />
        </div>
        <div class="weatherTemp">Seoul, 22℃</div>
    </div>
</body>
<script>
const API_KEY = "발급 받은 키";
const weatherIcon = document.querySelector(".weatherIcon");
const weatherTemp = document.querySelector(".weatherTemp");
navigator.geolocation.getCurrentPosition(
    (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(url)
            .then((response) => response.json())
            .then((data) => {
                weatherTemp.innerText = data.name + ", " + parseInt(data.main.temp) + "℃";
  				weatherIcon.src = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;
            });
    },
    () => alert("Not allowed!")
);
 </script>

&units=metric : 화씨->섭씨로 온도로 변환

날씨 API JSON파일

chrome json 파일 뷰어
https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh?hl=ko

{
  "coord": {
    "lon": 127.1151,
    "lat": 36.8306
  },
  "weather": [
    {
      "id": 802,
      "main": "Clouds",
      "description": "scattered clouds",
      "icon": "03d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 13.85,
    "feels_like": 12.02,
    "temp_min": 13.75,
    "temp_max": 15.99,
    "pressure": 1024,
    "humidity": 28
  },
  "visibility": 10000,
  "wind": {
    "speed": 2.57,
    "deg": 320
  },
  "clouds": {
    "all": 40
  },
  "dt": 1679982823,
  "sys": {
    "type": 1,
    "id": 8090,
    "country": "KR",
    "sunrise": 1679952263,
    "sunset": 1679996944
  },
  "timezone": 32400,
  "id": 1845759,
  "name": "Cheonan",
  "cod": 200
}

0개의 댓글