[JavaScript] getCurrentPosition 현재 위치 가져오기

빵호·2021년 7월 14일
0

JavaScript

목록 보기
6/28
post-thumbnail

메서드 사용법

navigator.geolocation.getCurrentPosition(success, error);

getCurrentPosition은 사용자의 위치(경도, 위도)를 가져오는 JavaScript의 API이다.

사용법은 해당 메서드의 첫 번째 인자로는 사용자의 위치를 가져오는데 성공했을 때 호출될 함수를

두 번째 인자로는 에러가 발생할 때 호출될 함수를 넣어주면 된다.

메소드 활용

이 메서드를 활용하면 아래와 같은 기능을 만들 수 있다.

  1. 위치를 지도에 표시
  2. 주위 가게나 상점 등을 표시
  3. 거주하는 지역의 날씨
  4. ... 등

이제 실제로 이 메서드를 활용한 코드를 보도록 하자.

const API_KEY ="API_KEY"

function Success(position) {
    const lat = position.coords.latitude; //위도
    const log = position.coords.longitude; //경도
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${log}&appid=${API_KEY}&units=metric` 
    fetch(url)
    .then((response) => response.json())
    .then((data) => {
      console.log(data.weather[0].main);
      console.log(data.main.temp);
    });
}
function Error() {
    console.log("위치를 찾지 못했습니다.");
}

navigator.geolocation.getCurrentPosition(Success, Error);
//성공 시 날씨와 온도가 콘솔에 표시됨 
//실패 시 위치를 찾지 못했다는 문장이 콘솔에 표시됨

위 코드를 실행하면 성공 시 getCurrentPosition에서 받아온 위도와 경도의 값을

openweathermap 사이트에 전달해서 현재 위치에 대한 날씨 관련 정보를 받아와 콘솔에 표시해 주고

실패 시 "위치를 찾지 못했습니다."라는 문장이 콘솔에 표시된다.


※ 위 코드는 API_KEY 값이 입력되어 있지 않아 에러가 발생한다. ※

직접 결과를 보고 싶다면 openweathermap에 들어가 회원가입 후 API_KEY를 받급 받도록 하자.

profile
늘 한결같이 꾸준히

0개의 댓글