티스토리 뷰

위도, 경도 값만 있다면 날씨 API를 통해서 해당 위치의 날씨를 알 수 있다.

사용할 API는 OpenWeather 의 API이다. 먼저 아래의 사이트에 가입하고 API키를 받아오자

(발급받은 직후는 인식되지 않고 한 30분 정도 기다려야 정상적인 키로 인식된다)

 

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Dashboard and Agro API We provide satellite imagery, weather data and other agricultural services that are based on geodata. By using Agro API , you can easily power your solution based on this information. Dashboard is a visual service where you can easy

openweathermap.org

 

지리좌표계와 API로 날씨 정보 얻어오기

지원하는 API는 여러 가지가 있어서 도시 이름, 도시 id값으로도 날씨를 알아올 수 있지만

이번에는 위도, 경도 값인 지리좌표계를 이용해서 날씨를 얻어올 것이다.

사용할 API는 다음과 같다.

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

 

 

인자를 차례대로 latitude 값, longitude 값, 계정 생성 후 얻은 api key를 전달해주면, 날씨 정보를 다음과 같이 얻을 수 있다.

{"coord": { "lon": 139,"lat": 35},
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 281.52,
    "feels_like": 278.99,
    "temp_min": 280.15,
    "temp_max": 283.71,
    "pressure": 1016,
    "humidity": 93
  },
  "wind": {
    "speed": 0.47,
    "deg": 107.538
  },
  "clouds": {
    "all": 2
  },
  "dt": 1560350192,
  "sys": {
    "type": 3,
    "id": 2019346,
    "message": 0.0065,
    "country": "JP",
    "sunrise": 1560281377,
    "sunset": 1560333478
  },
  "timezone": 32400,
  "id": 1851632,
  "name": "Shuzenji",
  "cod": 200
}

 

 

api 요청은 axios를 사용해서 하였고 문자열 사이에 변수를 넣기 위해 ES6의 최-신 문법이 사용된다.

바로 키보드에서 숫자1 왼쪽에 있는 택틱 문자를 사용한 것이다. 

  getWeather = async (latitude, longitude) => {
    const { data } = await axios.get(
      `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`
    );
  };

 

택틱으로 묶어준 문자열 안에서는 '$' 와 '{ }' 를 사용해서 바로 변수를 삽입할 수 있다.

위도, 경도, API_KEY 값을 미리 변수로 저장해두었다가 삽입할 수 있다.

댓글