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);
'Dev > JavaScript' 카테고리의 다른 글
showModalDialog 사용하기 (0) | 2022.05.20 |
---|---|
[JavaScript] Momentum App - 4.3 ToDo-List Loading To Dos (0) | 2022.05.03 |
[JavaScript] Momentum App - 4.2 ToDo-List Saving to Dos (0) | 2022.05.02 |
[JavaScript] Momentum App - 4.1 ToDo-List Deleting To Dos (0) | 2022.05.02 |
[JavaScript] Momentum App - 3. Quotes and Background (0) | 2022.05.02 |