openweathermap api로 현재 위치의 날씨정보 받아오기

람다람쥐·2023년 3월 25일
0

세미프로젝트 중 위치가 링크에 안들어가서 제일 오래 걸렸던 부분
메인에 현재 위치, 날씨 설명, 온도 등 출력하기

이전에 할일 : openweathermap 홈페이지에서 API 가져오기

const API_KEY="*"; //홈페이지에서 발급받은 api키

function onGeoOk(position) {
  
  	//js 내장함수로 현재 위도,경도 체크
    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`;
 	 			// 도시명으로 하려면 weather?q="+seoul+" ***
    
	fetch(url)
        .then(response => response.json())
        .then(data => {
	  console.log(lat,lon)
	  
      //url로 들어가면 json 코드 확인할 수 있음
	  const city=data.name;
	  const main=data.weather[0].main;
	  const desc=data.weather[0].description;
	  const temp=Math.round(data.main.temp);

      //출력
	  $("#w-city").text(city);
	  $("#w-temp").text(temp+"°");
	  $("#w-desc").text(desc);
	  $("#w-img").attr("src", "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png");
	  
}

function onGeoError() {
    alert("날씨를 제공할 위치를 찾을 수 없습니다.")
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
profile
반갑습니다람쥐

0개의 댓글