navigator.geolocation.getCurrentPosition(success, error)
Step 1. 사용자의 위치를 알아본다. (현재 위치의 위도와 경도)
function onGeoOk(position) {
console.log(position);
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
// 사용자의 현재 위치를 요청한다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
function onGeoOk(position) {
const lat = position.coords.latitude;
const lon = 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);
Step 2. 콘솔창에 있는 숫자들을 장소로 바꿔줄 서비스를 사용한다.
▶ http://openweathermap.org > API 메뉴 클릭 > Current Weather Data > API docs 클릭
▶ By geographic coordinates API call 복사해서 새창에다 주소를 붙여넣기 한 뒤에
주소중에서 각각 {lat}, {lon}, {API key} 안에 콘솔창에 있던 숫자들을 넣고
API key 경우엔 나의 프로필 Api keys > key 를 넣는다.
const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";
Step 3. JavaScript에서 url을 부르는 방법.
url을 설정한 뒤, 앞에서 숫자들을 ${lat}, ${lon}, ${API_KEY}로 백팁으로 감싸준다.
const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";
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}`;
console.log(url);
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
// 사용자의 현재 위치를 요청한다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
콘솔창 결과에 나온 url이 잘 실행하면 성공!!!!!
Step 4. fetch를 이용해서 URL 얻기
fetch(url); 해본다. ▶ 콘솔창 network창에 들어가 새로고침 clear버튼누르면, weather url정보를 얻을 수 있다.
const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";
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}`;
fetch(url);
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
// 사용자의 현재 위치를 요청한다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
만약, url을 수정할 수가 있는 선택옵션(optional)이 있는데, 그건 units=metric을 추가해본다.
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";
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는 promise (당장 일어나지 않고 시간이 좀 걸린 뒤에 일어나는 현상)
// URL을 fetch하고 response를 받아야 한다. 그리고 response의 json을 얻어야 한다.
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data.name, data.weather[0].main);
});
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
// 사용자의 현재 위치를 요청한다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
<div id="weather">
<span></span>
<span></span>
</div>
const API_KEY = "cc3f87264302b5e51f3a477bbe25e100";
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는 promise (당장 일어나지 않고 시간이 좀 걸린 뒤에 일어나는 현상)
// URL을 fetch하고 response를 받아야 한다. 그리고 response의 json을 얻어야 한다.
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}`;
});
}
function onGeoError() {
alert("Can't find you. No weather for you.");
}
// 사용자의 현재 위치를 요청한다.
navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
강의 끝!!!
'개발언어 > JavaScript' 카테고리의 다른 글
[JavaScript] 변수가 필요한 이유와 선언하는 방법 (0) | 2022.07.29 |
---|---|
[JavaScript] 데이터 타입 Data Types 의 종류 (0) | 2022.07.27 |
To Do List 만들기 (0) | 2021.09.03 |
Quotes and Background 명언 만들기 (0) | 2021.09.02 |
Clock만들기 (0) | 2021.09.01 |