javascript day7

김영목·2021년 10월 6일
0

이제 마지막 챕터로서 우리가 지금까지 해온 것들의 마지막 우리의 대략적인 위치와 날씨를 확인하는 것이다.


1단계 : where we are????
  
날씨와 위치를 알기 전에 우리가 현재 거주하는 공간의 위도와 경도를 알아야한다. 

그래서 여기서 사용되는 것이 navigator.geolocation이다. 

navigator.geolocation.getCurrentPosition();

위에서 중요한 것은 ()안에 들어가는 인자가 함수 2개라는 것이다. 
첫번째 인자는 객체가 현재 위치를 발견햇을 경우 그리고 두번째 인자는 위치발견에 실패했을 경우이다. 

그렇기 때문에 2개의 함수를 만들어야한다.

2단계 : 함수만들기

function onSuccess(position) {
	const lat1 = position.coords.latitude;
  	const long1 = position.coords.longitude;
  	// 위의 작업을 통해 우리가 원하는 위도와 경도를 얻었다.
  		
  	
}

function onFail() {
	alert("we can't find where you ars OTL")
}

navigator.geolocation.getCurrentPosition(onSuccess,onFail);

3단계 위치정도 api사용하기

const key = '~~~~~'

function onSuccess(position) {
	const lat1 = position.coords.latitude;
  	const long1 = position.coords.longitude;
  	// 위의 작업을 통해 우리가 원하는 위도와 경도를 얻었다.
  	
  	const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${apiKeys}&units=metric`;
  
  	// 여기서 중요하게 봐야하는 점은 해당 api에 변수를 할당하기 위해 백틱을 사용한 점이다. 
  
  4단계 : 화면에 보이도록 하기
  // html상에 지리날씨 정보를 위한 태그를 만들고 그것을 js상에서 변수로 할당하고 사용해보자. 
  
  	const span1 = document.querySelector('#weather span: first-child');
  	const span2 = document.querySelector('#weather span: last-child');
  	fetch(url).then(response => response.json()).then(data => {
    	span1.innerText = data.sys.country;
      	span2.innerText = `${data.weather[0].main} / ${data.main.temp}`;
    }
}
profile
안녕하세요 김영목입니다.

0개의 댓글