Java Script

Weather

_션샤인 2024. 8. 31. 20:53

8.0 Geolocation

 

1. function <navigator>

navigator.geolocation.getCurrentPosition()

 

1) getCurrentPosition(argument1, argument2)

 (argument1) the function that will be called if everything is okay.

 (argument2) the function that will be called if there is an error.

 

2) Declare function for getCurrentPosition

function onGoeOk(){}, functiononGeoError(){}

function onGoeOk(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(onGoeOk, onGeoError);

 

if its okay -> console.log "You live in 위도, 경도 "

if error -> execute alert

 

 

2. Need to use the service going to take this sort of numbers and turn them into a location

  ->  https://openweathermap.org/api

 

Weather API - OpenWeatherMap

 

openweathermap.org

 

 

 


 

 

8.1 Weather API

1) 

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

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

 

2) How to call url from Javascript

 (1) make valuable

 - const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`

 (2) units

 - default temp. is using Fahrenheit, If you want to change it put &units=metric on the url

 

3) get the url using fetch

fetch(url) -> you don't have to go to the url, Javascript will call the url.

fetch(url).then(response => response.json()).then(data => {

 const name = data.name;

 const weather = data.weather[0].main;

})

weather is array and we have to get the first element of the array and then we say main

 

 

** Error 

 

 

4) make a div on the html

    <div id="weather">
      <span></span>
      <span></span>
    </div>

 

5) modify fetch

    fetch(url)
        .then((response) => response.json())
        .then((data) => {
            const weather = document.querySelector("#weather span:first-child");
            const city = document.querySelector("#weather span:last-child");
            weather.innerText = `${data.weather[0].main} / ${data.main.temp}°C`;
            city.innerText = data.name;
    });