// Geolocation 8.0
: 브라우저와 관련된 정보를 컨트롤함, 브라우저에 대한 버전, 정보 종류 등 관련된 정보 제공
function onGeoOk(position) {
const lat = position.coords.latitude; // 위도 얻기
const lng = position.coords.longitude; // 경도 얻기
console.log("You live in", lat, lng);
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError)
// 사용자의 위치를 얻기 성공하면 전자를 실패하면 후자의 함수 실행
// Geolocation 8.0
✔ weather API 사용
fetch() 함수는 첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환
반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject
fetch(url, options)
.then((response) => console.log("response:", response))
.catch((error) => console.log("error:", error));
https://programmingsummaries.tistory.com/325 링크 참고 (솔직히 뭔 소린지 잘 모르겠음..)
암튼 날씨도 완성!
결과
const API_KEY = "9785dfe45ad749fc5ec1d09983fee741";
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(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}°C`;
});
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError)
[노마드코더] 바닐라JS 와 비교 및 리액트 기초 문법 (0) | 2022.01.26 |
---|---|
[노마드코더] 바닐라JS 공부 7일차(To Do List) (0) | 2022.01.15 |
[노마드코더] 바닐라JS 공부 6일차(Quotes and Background: Math객체 난수) (0) | 2022.01.11 |
[노마드코더] 바닐라JS 공부 5일차(clock :setInterval, setTimeout, Date 객체, padStart) (0) | 2022.01.11 |
[노마드코더] 바닐라JS 공부 4일차(Login 구현:preventDefault, localStorage) (0) | 2022.01.04 |