본문 바로가기
공부/javascript

2022.06.17 - weatherAPI 사용해보기

by 기묜몬 2022. 6. 17.

1. navigator 함수를 이용해 사용자의 위치를 알아내는 코드 작성

- navigator.geolocation.getCurrentPosition(onOk, onError);
 => getCurrentPosition(실행함수, 에러가 발생했을때 실행할 함수)

 

- navigator.geolocation 은 Chrome 50 버젼 이후로 HTTP 환경에서 사용이 Deprecate 되어 HTTPS 환경에서만 사용 가능. 

host 설정을 개인 ip -> localhost:port/index.html  로 변경하여 접속하기 

 

2. onError() - 에러 발생했을때 함수 실행

에러 발생시 사용자에게 알려주기 위해 alert("에러"); 간단 작성해주기

 

3. onOk() - 정상 함수 실행시

경도와 위도를 입력하여 위치를 전달해준다. 

function onGeoOk(position){
const lat = position.coords.latitude; // 경도 
const lng = position.coords.longitude; // 위도 
console.log("You live in", lat, lng);
}

 

4. 날씨API 가져오기 

1) 해당 홈페이지 접속 후 가입 -> 해당 메일 확인하여 승인하기 

https://openweathermap.org/ 

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

 

2) API -> Current Weather Data -> API doc 

https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}

=> 빨강색 부분 ${} 삭제 후 내 위치 값으로 넣기 (경도,위도, api_key)

API_KEY는 오픈웨더맵 홈페이지의 my api keys 에 있음!

 

3)  request 확인

 

4) fetch() 함수로 원격 api 호출

fetch() 함수는 첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환한다.

반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject한다.