자바스크립트

[javascript] 현재 위치 기반 날씨 알려주기

grin-quokka 2019. 8. 14. 21:53

날씨 API

  • https://home.openweathermap.org/api_keys
    • 회원가입을 하고, 발급된 api key를 복사한다. 
  • 현재 좌표 가져오기
    • navigator.geolocation.getCurrentPosition(위치 가져오기에 성공 했을 때 실행할 함수, 실패 했을 때 함수)
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      let latitude, longitude;
       
      navigator.geolocation.getCurrentPosition(position => {
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        
      });
       
       
      //좌표에서 얻은 latitude와 longitude, 발급받은 API key를 넣어준다.
       
      fetch(
          `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`
        )
          .then(response => {
            return response.json();
          })
          .then(json => {
          // 오늘의 온도 units=metric을 붙였기 때문에 섭씨로 나온다.
          console.log(json.main.temp);
          });
      cs