JS: 노마드 코더 8강 정리

ChoHyerin·2023년 5월 18일
0

Javascript

목록 보기
7/7

8.0 Geolocation

weather.js

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);

navigator.geolocation.getCurrentPosition()
: 브라우저에서 위치 좌표를 준다. 위도, 경도, 고도, 장치의 이동방향, 장치의 현재속도, gps, 와이파이 등
** 참고: 사용자의 위치 변화 발생시 호출되는 함수는 watchPosition()

이때 getCurrentPosition 은 2개의 argument가 필요하다. 앞쪽에는 모든 게 잘 됐을 때 실행될 함수인 onGeoOk 함수를, 뒤에는 실패했을 때 실행될 함수인 onGeoError 함수를 입력함

onGeoError() 함수가 실행될 때
: 에러가 났다는 것을 사용자에게 알려주기 위해서 alert("Can't find you. No weather for you."); 해 줌

onGeoOk 함수가 실행될 때
: 자바스크립트가 position으로 user의 위치를 전달,
position은 object 이고 위도와 경도 값이 들어있음

function onGeoOk(position){
	const lat = position.coords.latitude;
	const lng = position.coords.longitude;
	console.log("You live in", lat, lng);
}

positon.coords.latitude와 position.coords.longitude 를 변수에 저장하고 console.log를 해서 사용자에게 보여준다.


8.1 Weather API

: 위도와 경도를 장소로 바꿔주는 API 서비스를 사용하고 사용자 위치에 대한 정보를 제공하는 url을 불러온다.

index.html

	<div id="weather">
      <span></span>
      <span></span>
    </div>
	<!--새로 추가, 날씨관련 내용 표시하기 위해-->
    <script src="js/greetings.js"></script>
    <script src="js/clock.js"></script>
    <script src="js/quotes.js"></script>

weather.js

const weather = document.querySelector("#weather span:first-child");
const city = document.querySelector("#weather span:last-child");
const API_KEY = "241051bf13976dd3ddf8b8d9f247255e";

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) => {
      city.innerText = data.name;
      weather.innerText = `${data.weather[0].main} / ${data.main.temp}`;
    });
}
function onGeoError() {
  alert("Can't find you. No weather for you.");
}
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
const API_KEY = "1545879515889df25c23857021328cf1";

function onGeoOK(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  console.log("You live in", lat, lon);
  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}`;
    }); //js가 url 부름, promise(시간이 좀 걸린 뒤에 일어나는 것)
}

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

navigator.geolocation.getCurrentPosition(onGeoOK, onGeoError);

0개의 댓글