상세 컨텐츠

본문 제목

현재 기온 알려주는 스크립트

지식·동향/컴퓨터정보

by 그뤠잇팔공케이 2024. 7. 10. 16:19

본문

반응형
SMALL

https://api.openweathermap.org 가셔서 api 얻으시고

const LS_GPSName = 'GPS';
const API_KEY = '자신의 API 입력하세요';
const weather = document.querySelector(".weather");

function getWeather(lat,lon){
    fetch(
        `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`
        //api 호출해서 위도,경도,appid키값,화씨를 섭씨로 바꾸기 등을 넣어서 정보를 가져온다.
        ).then(function(data) {
            return data.json();
        }).then(function(json){
            const temper = json.main.temp;
            const place = json.name;
			weather.innerText = `${temper}°C`;
            //weather.innerText = `${place}의 현재기온은 ${temper}°C`;

                        //속성으로 css 설정
            //weather.setAttribute('style','font-size : 30px; color : white;');

                        //프로퍼티로 css 설정
            weather.style.color = 'white';
            weather.style.fontSize = '18px';
        });        
    }

    //featch는 IE에선 작동이 안된다
    //AJAX의 상위호환 같은것인데 IE에서는 개발이안되서
    //국내에선 사용하기가 조금 꺼려진다
    //국내에선 되도록 AJAX를 호출하는게 나을거같다


function LS_SaveGPS(GPSObj){
    localStorage.setItem(LS_GPSName,JSON.stringify(GPSObj));
}
function SaveGPSSuccess(position){
    const lat = position.coords.latitude; //위도 얻기
    const lon = position.coords.longitude; //경도 얻기
    const GPSObj = {
        lat,
        lon
    }
    LS_SaveGPS(GPSObj);
    getWeather(lat,lon);
}

function SaveGPSError(){
    console.log("failed");
}

function SaveGPS(){
    navigator.geolocation.getCurrentPosition (SaveGPSSuccess,SaveGPSError);
    //navigator.geolocation 객체를 이용해서 gps 정보를 얻는다
    //getCurrentPosition빠른 응답 / 정확도는 낮음
    // getCurrentPosition 은 (첫번째인자,두번쨰인자)\
    //첫번쨰인자는 석세스 콜백 함수고
    //두번째 인자는 에러 콜백 함수다.
}

function loadGPS(){
    const LS_GPSInfo = localStorage.getItem(LS_GPSName);
    if(LS_GPSInfo === null || LS_GPSInfo === undefined){
        //GPS정보얻기
        SaveGPS();
    } else {
        const parseGPS = JSON.parse(LS_GPSInfo);
        //GPS 정보 가져오기
        getWeather(parseGPS.lat,parseGPS.lon);
    }
}

function init(){
    loadGPS();
}

init();

weather.js 스크립트 저장하시고

 <p class="weather"></p>
		<script src="weather.js"></script>

html 에서 이렇게 사용하시면 됩니다.

 

반응형
LIST

관련글 더보기