[javascript] - navigator 및 날씨API 가져오기

eunbi·2020년 3월 28일
2

javascript

목록 보기
3/8

API

  • 다른 서버로부터 손쉽게 데이터를 가져올 수 있는 수단
  • 특정 웹사이트로부터 데이터를 얻거나 컴퓨터끼리 소통하기 위해 고안
  • navigator 객체는 브라우저 공급자 및 버전 정보 등을 포함한 브라우저에 대한 다양한 정보를 저장하는 객체

  • appVersion, userAgent 등으로 사용자 브라우저 정보를 알 수 있다.

getCurrentPosition

navigator.geolocation.getCurrentPosition(success callback, error callback)

  • 현재 사용자 위치 정보 가져오는 메서드이다
성공했을때 함수(position){ /// position값을 인자로 받는다
    
}

위의 매개변수 position안에는 위치 정보가 담겨 있다(위도 경도 등 가져올 수 있음)
position.coords.longitude(경도)
position.coords.latitude(위도)

  • position의 다양한 메서드들을 확인해보자!
GeolocationPosition
coords: GeolocationCoordinates
latitude: 37.5325655
longitude: 126.70750609999999
altitude: null
accuracy: 1278
altitudeAccuracy: null
heading: null
speed: null
__proto__: GeolocationCoordinates
timestamp: 1585378750612
__proto__: GeolocationPosition

watchPosition()

navigator.geolocation.watchPosition(success callback, error callback)

  • 위치 정보가 변경 될 때는 사용

  • 만약 위치 정보가 변경(장치가 움직였거나 좀 더 정확한 위치 정보가 도착했을때)되었다면 갱신된 위치 정보로 호출되는 콜백 함수를 지정할 수 있습니다.

  • getCurrentPosition() 함수에서와 마찬가지로 옵션인 에러 콜백 함수도 반복적으로 호출될 수 있습니다.

  • 숫자로 된 ID를 반환하며, watcher를 식별하는데 사용.

  • clearPosition() 메서드를 사용하여 사용자 위치 추적을 중단.

  • 참고 :
    https://developer.mozilla.org/ko/docs/WebAPI/Using_geolocation

    js는 웹사이트로 request 보내고 응답을 통해서 데이터를 얻을수 있는데 가져온 데이터를 refresh없이도 나의 웹사이트에 적용시킬 수 있다
    => ex) 이메일 들어올때 실시간으로 메일이 오는것 확인
    보이지 않는 곳에서 js가 계속 데이터를 읽어옴

날씨 API 받아오기

  1. API keys를 가져와서 코드에 붙여넣음

  2. API => Current weather data => By geographic coordinates(API call)을 가져옴

  3. 가져온 API call 앞에 https:// + api + 각 위치에 latitude,longitude 넣어준뒤 + &appid=${API_KEY}를 넣어주고 fetch하기

     fetch(
           `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`
           )
  1. 이렇게 가져온 데이터는 섭씨이기 때문에 화씨로 변경해야함

    Units format을 보면
    => For temperature in Celsius use units=metric
    이렇게 적혀있다
    https://openweathermap.org/current#parameter

 fetch(
       `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric` // 끝부분에 추가
       )

불러온 날씨 호출하기

  • then() : 데이터가 완전히 들어온 다음 호출(데이터 넘어오는데 시간이 걸릴 수 도 있기 때문)

       fetch(
           `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`
       ).then(function(response){
           console.log(response)
       })
  • fetch가 끝난 후 then실행
  • 여기까지는 network 정보임 => json으로 변경하기

  fetch(
        `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`
    ).then(function(response){ //network 정보 => json으로 변경
      return response.json();
    }).then(function(json){
        json//으로 할일
    })
  • json정보로 변경 됨
profile
프론트엔드 개발자입니다 :)

0개의 댓글