하루를살자

JS Clone Project [Weather] - 1, weather API 본문

JS

JS Clone Project [Weather] - 1, weather API

Kai1996 2021. 12. 9. 18:01

Key Points 

- use of open API. 

- Weather API from 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

- Use of API URL 

//Be sure to make the API_KEY as string
const API_KEY ="cc9adc5ce92a3b5e53924dedbc9ca38a";

//if getCurrentPosition is succeed , it calls onGeoOk function with geolocation object information
function onGeoOk(pos){
    const lat = pos.coords.latitude; 
    const long = pos.coords.longitude;

    console.log(lat,long);
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${API_KEY}&units=metric`;
    fetch(url)
    .then(response => response.json())
    .then(data =>{
        const city= document.querySelector("#weather span:first-child");
        const weather = document.querySelector("#weather span:nth-child(2)");
        const temp =  document.querySelector("#weather span:nth-child(3)");

        city.innerHTML = data.name;
        weather.innerHTML = data.weather[0].main;
        temp.innerHTML = `${data.main.temp} Celcius`;
        
    
    });
}

function onGeoError(){
    alert("Can't find you.!");
}

//getCurrentPosition requires 2 arugments, 1. successfull callback 2. fail callback
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);

 

Staff learned 

- use fetch(URL) to get a response to that URL. 

--> fetch returns Promise which means something is going to happen after once the page get response from the fetch. 

--> fetch(URL).then() : refers that do something once the fetch is completed. In this case, 

"fetch(URL).then(response=> response.json()).then(data =>{

    console.log(data.weather[0].main);

}) "

response.json() ==> get the response as JSON

data =>{} : make use of the recieved data.

 

Comments