본문 바로가기
Dev/JavaScript

[JavaScript] Momentum App - 5. Weather API

by 코딩삐약 2022. 5. 3.
navigator.geolocation.getCurrentPosition(success, error); - 함수 

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

 

Geolocation.getCurrentPosition() - Web APIs | MDN

The Geolocation.getCurrentPosition() method is used to get the current position of the device.

developer.mozilla.org

 

현재 날씨 알려주는 API 

https://openweathermap.org/current#geo

 

Current weather data - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! We collect and process weather data from different sources such as global and local weather models, satellites, radars and a vast network of weather stations. Data is avai

openweathermap.org

// weather.js

const API_KEY = "your api key~~~"

function onGeoOk(position) {
    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`
    
    //fetch : JavaScript가 url을 요청함
    // promise 요청 후 잠시 시간이 걸리므로 then사용
    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} / ${data.main.temp}`;
        //weather는 array라서 0번째 선택.
    });
}

function onGeoError(){
    alert("Can't find you. No weather for you.");
}

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);