Land of Joe

[JavaScript] navigator.geolocation.getCurrentPosition(success함수,error함수) 본문

🌐 Web/🟡 JavaScript

[JavaScript] navigator.geolocation.getCurrentPosition(success함수,error함수)

Arendt 2023. 5. 15. 22:36

Step1. 현재 위치의 위도, 경도 숫자 얻기

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

 

 

Step2. 위도, 경도 숫자를 장소로 바꿔준다

https://openweathermap.org/current

 

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

openAPI를 활용

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}

 

{lat}부분에 위 과정을 통해 얻은 위도(latitude) 값을 넣어주고

{lon}부분에 경도(longitude) 값을 넣어주고

{API key} 부분에 나의 개인 API key 값을 넣어주면 해당 위치의 날씨 정보가 나온다

 

 

javascript가 url을 직접 불러오도록 하는 것: fetch(url)

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

개인 API key 값을 넣어주고 돌리면