본문 바로가기

JavaScript

[자바스크립트] 정리 7

1. 위치정보 불러오기 

- navigator.geolocation.getCurrentPosition(successCallback, errorCallback) 을 사용 

- position 객체를 전달 받아서 사용할수 있다.

navigator.geolocation.getCurrentPosition(onGeoOK, onGeoError);

function onGeoOK(position){
    const la = position.coords.latitude;
    const lo = position.coords.longitude
    console.log(`You live in ${la}, ${lo}`);
}

function onGeoError(){
    alert("I can't find you!!");
}

 

2.  위도, 경도 값으로 날씨정보 불러오기 

- OpenWeatherMap API를 사용하자 

Current weather data - OpenWeatherMap

 

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

- sign up하고 API KEY를 얻어오자. 

- latitude(위도), logitude(경도), API_KEY를 가지고 url을 완성해주자. 

- fetch(url) : url을 요청(requeset)하고 기다린다. , 개발자도구 Network에서 확인가능. 

- then: 응답(response)를 받으면 이후 실행한다. 

- response.json() -> 날씨정보를 담은 객체를 받아온다. 

- 이후 원하는 값을 HTML에 출력. 

navigator.geolocation.getCurrentPosition(onGeoOK, onGeoError);
const API_KEY = "63afcf14c93211ad7910a4e0c1a8648d";

function onGeoOK(position){
    const lat= position.coords.latitude;
    const log = position.coords.longitude
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${log}&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");
            weather.innerText = data.weather[0].main;
            city.innerText = data.name;
        });
}

function onGeoError(){
    alert("I can't find you!!");
}

 

 

 

'JavaScript' 카테고리의 다른 글

Hash and Map  (0) 2022.04.28
REST API  (0) 2022.02.03
[자바스크립트] 정리 6  (0) 2022.01.19
[자바스크립트] 정리5  (0) 2022.01.18
[자바스크립트] 정리4  (0) 2022.01.18