본문 바로가기
  • think normal
새로워지기/마흔의 생활코딩

cursor IDE_coding test01 - weather api

by 청춘만화 2023. 12. 8.

open api를 활용해서 오늘의 날씨를 알려주는 간단한 html 코드 만들어보기 

 

 

1. html 파일을 만든다

2. html엔터를 쳐서 기본 프레임을 구성한다

3. 바디 사이에 마우스로 일부 영역을 잡고 Add to Chat을 클릭한다

 

 

4. Chat 영역에 구성하고자 하는 내용을 입력한다.

 

 

5. 코드를 복사해서 붙여넣는다.

6. 안내해준 사이트에 가입하고 apikey를 발급받아 입력한다

 

 

7. 브라우저로  코드를 실행한다 

 

 

8. Chat 화면에서 아래와 같이 상세 프롬프트를 입력 

조금 전 코드에
1. css를 활용해서 화면에는 '오늘의 수원 날씨 : {날씨 정보}'를 가운데 타이틀 형태로 보여주고 지도는 화면 가운데 60%영역으로 카드형태로 보이도록 수정해줘
2. 날씨 정보 단어 옆에 owm-weather-icon아이콘과 함께 표시해주고 그 옆에 날씨정보와 바람 세기 정보를 보여주는 코드를 추가해줘

 

 

 

 

 


전체 코드

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        #title {
            text-align: center;
            font-size: 2em;
            margin-top: 20px;
        }
        .map {
            height: 60vh;
            width: 60%;
            margin: 20px 0;
            border: 1px solid black;
        }
        #hourlyForecast, #dailyForecast {
            width: 60%;
            height: 60vh;
        }
        .ol-attribution{
            display: none;
        }
    </style>
</head>
<body>
    <div id="title"></div>
    <div id="map" class="map"></div>
    <div id="airPollution"></div>
    <canvas id="hourlyForecast"></canvas>
    <canvas id="dailyForecast"></canvas>
    <script>
        var apiKey = 'f770c934b0cb93b54e8c96cd14995682';
        var city = 'Suwon,KR';

        // 오늘의 날씨 정보 가져오기
        fetch('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=' + apiKey)
        .then(function(resp) { return resp.json() })
        .then(function(data) {
            var weatherIcon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
            document.getElementById('title').innerHTML = '오늘의 수원 날씨: <img src="' + weatherIcon + '"> ' + data.weather[0].main + ', 바람 세기: ' + data.wind.speed;
            var lat = data.coord.lat;
            var lon = data.coord.lon;

            // 대기 오염 정보 가져오기
            fetch('http://api.openweathermap.org/data/2.5/air_pollution?lat=' + lat + '&lon=' + lon + '&appid=' + apiKey)
            .then(function(resp) { return resp.json() })
            .then(function(data) {
                document.getElementById('airPollution').innerHTML = '대기 오염 지수: ' + data.list[0].main.aqi;
            })
            .catch(function() {
                console.log("error");
            });

            // 7일간의 날씨 예보 가져오기
            fetch('https://api.openweathermap.org/data/2.5/onecall?lat=' + lat + '&lon=' + lon + '&exclude=minutely,alerts&appid=' + apiKey)
            .then(function(resp) { return resp.json() })
            .then(function(data) {
                var forecastDiv = document.getElementById('forecast');
                for (var i = 0; i < 7; i++) {
                    var day = data.daily[i];
                    forecastDiv.innerHTML += '<p>Day ' + (i + 1) + ': ' + day.weather[0].main + '</p>';
                }

                // 시간당 예보 그래프 그리기
                var ctx = document.getElementById('hourlyForecast').getContext('2d');
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: data.hourly.map((_, i) => i + '시간 후'),
                        datasets: [{
                            label: '온도 (°C)',
                            data: data.hourly.map(h => h.temp - 273.15),
                            borderColor: 'rgb(255, 99, 132)',
                            yAxisID: 'y',
                        }, {
                            label: '강수 확률 (%)',
                            data: data.hourly.map(h => h.pop * 100),
                            borderColor: 'rgb(54, 162, 235)',
                            yAxisID: 'y1',
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                beginAtZero: true
                            },
                            y1: {
                                beginAtZero: true
                            }
                        }
                    }
                });

                // 8일간 예보 그래프 그리기
                var ctx = document.getElementById('dailyForecast').getContext('2d');
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: data.daily.map((_, i) => i + '일 후'),
                        datasets: [{
                            label: '온도 (°C)',
                            data: data.daily.map(d => d.temp.day - 273.15),
                            borderColor: 'rgb(255, 99, 132)',
                            yAxisID: 'y',
                        }, {
                            label: '강수 확률 (%)',
                            data: data.daily.map(d => d.pop * 100),
                            borderColor: 'rgb(54, 162, 235)',
                            yAxisID: 'y1',
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                beginAtZero: true
                            },
                            y1: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            })
            .catch(function() {
                console.log("error");
            });

            // 지도 표시하기
            var map = new ol.Map({
                target: 'map',
                layers: [
                    new ol.layer.Tile({
                        source: new ol.source.OSM()
                    })
                ],
                view: new ol.View({
                    center: ol.proj.fromLonLat([lon, lat]),
                    zoom: 10
                })
            });
        })
        .catch(function() {
            console.log("error");
        });
    </script>
</body>
</html>

댓글