GitHub

https://github.com/Backcoder-June

BackCoder 기록 그리고 숙달

Back to the API

주소찾기API => Kakao GeoCoder => Kakao Map API 연계, 거리 계산 활용하기

Backcoder 2022. 11. 16. 14:43

(1) 주소찾기 API 는 흔히 우리가 사용하는 주소찾기 API 입니다. 

 

(2) 위의 주소찾기 API 에서, '정확한 주소명' data 를 받을 수 있기 때문에, 

Kakao Geocoder API에 이  '정확한 주소명' 을 이용하면 

해당 주소의 '위도, 경도 좌표' 를 받아올 수 있습니다. 

	
    // ... 다음 주소찾기 API 에서 전체주소를 갖는 변수 address를 이용해 kakaoGeocoder API 실행
    document.getElementById("sample6_address").value = address;
			KakaoGeocoder(address);

 

 

- 기본적인 좌표는 (123.456789, 234.5678912) 의 형태로 주어지기 때문에, 

이를 toString()substring() 등을 활용해서, 위도, 경도로 따로 값을 뽑아내 둡니다. 

 

이 위도, 경도 data 를 이용해서 KakaoMap API를 실행합니다. 

kakaoMap(meetingLat, meetingLon); 

// 카카오 geoCoder API 	
function KakaoGeocoder(address) {
	// 주소-좌표 변환 객체를 생성합니다
	var geocoder = new kakao.maps.services.Geocoder();

	// 주소로 좌표를 검색합니다
	geocoder.addressSearch(adress, function (result, status) {

		// 정상적으로 검색이 완료됐으면 
		if (status === kakao.maps.services.Status.OK) {

			var coords = new kakao.maps.LatLng(result[0].y, result[0].x);
			var strCoords = coords.toString(); 
			var meetingLat = strCoords.substring(1, strCoords.indexOf(','));
			var meetingLon = strCoords.substring(strCoords.indexOf(',')+2, strCoords.length-1);
			
			let meetingcoords = [];
			meetingcoords.push(meetingLat);
			meetingcoords.push(meetingLon);
			localStorage.setItem('mapAddress' + ${sessionCoords} + ${chatRoomInfo.id}, meetingcoords);
			
			kakaoMap(meetingLat, meetingLon);
		}
		
	}); // addressSearch     
} // kakaoGeocoder

 

이렇게 하면

(1) 주소찾기 => 전체주소 Data 

(2) 전체주소 Data => Kakao Geocoder 위도, 경도 

(3) Kakao Geocoder 위도, 경도 => Kakao Map API 

 

위의 과정을 거치며, 

주소찾기 입력시 => Kakao Map 에 해당 위치를 띄워서 보여줄 수 있었습니다. 

 

이를 응용한다면, 

a. 세션에 넣어둔 id 정보를 통해 주소 위도 경도를 가져오고 

b. 새로 주소찾기로 입력된 위도 경도 정보를 가져와서 

a. 현재 세션과 b. 주소찾기 ( 약속장소 ) 위치 2개를 kakaomap 에 보여줄 수 있었습니다. 

 

위와 같이, 두 위치정보 ( 위도, 경도 ) 를 갖고 있다면, 

SELECT  
    (6371*acos(cos(radians((select substring(coords, 2, locate(',',coords)-2) from MEMBERS where userid = #{buyerId})))*cos(radians(((select substring(coords, 2, locate(',',coords)-2) from MEMBERS where userid = #{sellerId}))))*cos(radians((select substring(coords, locate(',',coords)+2, locate(')',coords)-locate(',',coords) - 2) from MEMBERS where userid = #{sellerId} ))
    -radians((select substring(coords, locate(',',coords)+2, locate(')',coords)-locate(',',coords) - 2) from MEMBERS where userid = #{buyerId})))+sin(radians((select substring(coords, 2, locate(',',coords)-2) from MEMBERS where userid = #{buyerId})))*sin(radians((select substring(coords, 2, locate(',',coords)-2) from MEMBERS where userid = #{sellerId})))));

이미 만들어져 있는 위도, 경도 좌표를 통해 거리를 계산하는 위와 같은 공식을 SQL 등에서 활용해서 

거리 계산을 해 활용할 수 도 있었습니다. 

 

API 는 사용자마다 필요로 하는 data 가 다르기 때문에 대게가 최소단위로 구성이 되어 있는 것 같습니다. 

이를 적절하게 연결시켜 필요한 data 를 가져다 활용할 수 있는 능력도 계속 키워나가야 겠습니다.

'Back to the API' 카테고리의 다른 글

DAUM 주소찾기 API 동 주소 활용하기  (2) 2022.11.16