날씨 기능 만들기
(weather API)
- 만들고 싶은 기능
- 먼저 자신이 있는 위치를 불러올 수 있는 함수가 있다. 파라미터에는 성공 시 함수와, 실패 시의 콜백함수를 넣어준다.
navigator.geolocation.getCurrentPosition(GeoOk, GeoError)
- 성공과 실패했을 때의 콜백함수를 넣어주었다. 성공시 파라미터를 생성해주고 콘솔에 출력해본다.
function GeoOk(position){
console.log(position)
}
function GeoError(){
alert("Can't find you. No Weather for you.")
}
콘솔창에서 데이터 값을 확인해볼 수 있는데, latitude, longitude를 확인할 수 있다. (위도, 경도)
- 위도와 경도를 출력해보자.
function GeoOk(position){
console.log(position.coords.latitude)
console.log(position.coords.longitude)
}
이 경도와 위도를 통해 날씨를 알려주는 API를 제공해주는 사이트가 있다.
https://openweathermap.org/api
여기에 가입해서, Current Weather Data를 사용할 수 있다.
Weather API - OpenWeatherMap
Please, sign up to use our fast and easy-to-work weather APIs. As a start to use OpenWeather products, we recommend our One Call API 3.0. For more functionality, please consider our products, which are included in professional collections.
openweathermap.org
API를 불러오려면 URL창에 lat, lon, api key를 입력하고 엔터치면 데이터 값을 얻을 수 있다. api는 profile에 개인 api키가 있다.
api를 호출하니 아래와 같은 데이터 값이 나왔다. 날씨는 화씨로 표현되고 있기 때문에 섭씨로 표현하고 싶다면 url창 맨뒤에 &units=metric를 입력해주면 된다.
이제 이 데이터값을 javascript로 호출해 사용해보자.
- 먼저 url을 javascript에서 호출한다.
const API_KEY = "3c98b8415874832af31ce4ea1b2af530";
function GeoOk(position){
const lat = position.coords.latitude;
const lng = position.coords.longitude;
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
fetch(url)
}
url을 호출할 때에는 fetch 함수로 url을 불러온다. 나는 나의 api값과 url을 변수로 저장했다.
- url 호출 후, 성공했을 때, 데이터 값을 가져온다. 서버에서 가져온 object 형식이니, json을 적어서 받고, 그 값들을 변수로 저장해준다.
- html 파일에는 weather id를 가진 div 안에 span태그 두 개를 넣어두었다.
function onGeoOk(position) {
console.log(position);
const lat = position.coords.latitude;
const lng = position.coords.longitude;
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}`;
fetch(url)
.then((response) => response.json())
.then((data) => {
const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
city.innerText = data.name;
weather.innerText = data.weather[0].main;
});
}
최종 JS
const API_KEY = "3c98b8415874832af31ce4ea1b2af530";
function onGeoOk(position) {
console.log(position);
const lat = position.coords.latitude;
const lng = position.coords.longitude;
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}`;
fetch(url)
.then((response) => response.json())
.then((data) => {
const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
city.innerText = data.name;
weather.innerText = data.weather[0].main;
});
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);