[JavaScript] GeoLocation api, 카카오 좌표 -> 주소 변환계 구현하기

Lee Seung Jae·2021년 3월 23일
0

GeoLocation API

GeoLocation API는 navigator.geolocation 객체를 통해 사용을 할 수가 있다.

현재위치 가져오기

getCurrentPosition() 메소드를 호출해서 사용자의 현재위치를 얻을 수 있다.
getCurrentPosition()은 사용자의 위치를 탐지하는 비동기 요청을 초기화하고, 위치 관련 하드웨어에 최신 정보를 요청한다.

HTML 예시

<button id="btnTest">좌표얻기</button>

JavaScript 예시

var options = {
	enableHighAccuracy : true,
	timeout : 5000,
	maximumAge : 0
};
function success(pos) {
	var crd = pos.coords;
	console.log('위도 : ' + crd.latitude);
	console.log('경도: ' + crd.longitude);
	lat = crd.latitude;
	lon = crd.longitude;
};

function error(err) {
	console.warn('ERROR(' + err.code + '): ' + err.message);
};

$("#btnTest").click(function() {
	navigator.geolocation.getCurrentPosition(success, error, options);
})

출처 - https://developer.mozilla.org/ko/docs/Web/API/Geolocation_API/Using_the_Geolocation_API

진행을 해주게되면 좌표얻기라는 버튼을 클릭했을때
위와 같은 이미지가 출력됨과 동시에 개발자 도구창의 콘솔에서는 현재 위치를 기반으로 한 위도와 경도가 출력되게 된다.

그럼 이것을 토대로 카카오 좌표를 주소로 변환하는 변환계를 사용하여 현재 주소를 얻는것을 진행하면 되겠다.

$.ajax({
	url : 'https://dapi.kakao.com/v2/local/geo/coord2address.json?x=' + lon +'&y=' + lat,
    type : 'GET',
    headers : {
      'Authorization' : 'KakaoAK {REST_API_KEY}'
    },
    success : function(data) {
      console.log(data);
      }
    },
    error : function(e) {
      console.log(e);
    }
  });

출처 - https://developers.kakao.com/docs/latest/ko/local/dev-guide#coord-to-address
나는 Ajax로 REST API를 GET방식 처리를 진행하여 위와 같이 코드를 구현하였다.

{meta: {…}, documents: Array(1)}
  documents: Array(1)
    0:
      address:
      address_name: "지역 구 동 번지수"
      main_address_no: "1124"
      mountain_yn: "N"
      region_1depth_name: "지역"
      region_2depth_name: "구이름"
      region_3depth_name: "동이름"
      sub_address_no: "59"

console.log(data); 를 실행했을때 위와같이 자료가 나오게 되므로 데이터를 가져다가 쓰면 될것 같다.

이상으로 현재 좌표로 주소를 구현하고자 할때 쓰는 방법을 알아보았다.

profile
💻 많이 짜보고 많이 경험해보자 https://lsj8367.tistory.com/ 블로그 주소 옮김

0개의 댓글