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 에서 이렇게 사용하시면 됩니다.
웹페이지에 SNS[페이스북,트위터,네이버, 공유버튼,주소복사 달기 (0) | 2024.06.25 |
---|---|
특수문자 (0) | 2024.05.12 |
html 페이지에 파티클 적용 (0) | 2024.03.06 |
html title 실시간 변경되는 스크립트 타이틀 확인해주세요. (0) | 2023.09.30 |
전공 공부에 지친 당신! 진로에 고민이 많은 당신!나에게 잘 어울리는 학과는 무엇일까요? (0) | 2023.09.28 |