81일차 길찾기 코드 수정, 랜덤 길찾기(2)

이해찬·2023년 10월 30일
0

항해일지

목록 보기
34/35

2023.10.31


💻 개선 방향

  1. 카테고리에 맞는 정확한 지명과 주소의 매칭
  2. 효율적인 길찾기 경로 생성
  3. 도로교통 정보를 반영 -> 거리가 더 멀어지더라도 정체 -> 서행으로 드라이브를 할 수 있게
  4. 출발지 도착지 명확하게 표시


✅ 1. 카테고리에 맞는 정확한 지명과 주소의 매칭= 정확한 address + 지명

  • 키워드를 입력하면 해당 주소를 반환해주는 키워드 api 활용
  • address_name시, 구 + 키워드 조합 -> 주소 요청 + 해당 카테고리 맞는지 검사
  • 해당 키워드 place_name 요청 -> address_name 가져와서 좌표로 변환

📟 기존의 문제

  • 위에서 언급한 것처럼 인천 계양구 방축동뒷동산 이라는 주소가 불일치
  • 그러나 키워드api를 활용해서 시 , 구 + 키워드 => 정확한 해당 주소가 나옴


👇 시 + 구 + 키워드를 조합하면 정확한 주소로 매칭이 가능



👇 시 + 구 + 키워드를 조합하면 정확한 주소로 매칭이 가능




💻 시도1

  • 카테고리api + 키워드api 활용 했으나, 키워드도 동일한 좌표
  • 해당 uri주소를 눌렀을 때, 정확한 위치가 나와서 새로운 좌표로 나오는 줄 알았으나
  • uri만 정확한 지표가 나오고 x,y 좌표값은 동일하다.
  • 해당 좌표의 상세정보가 address_name 이며, 좌표는 상세정보로 고정되어 있다.
  • 더 정확한 좌표는 uri를 타고 들어가서 지도를 클릭해야 나온다.
  • 상세 주소에 가장 근접한 주소로 나오는 듯 하다.(차도 기준)

👉 placeName 과 addressName의 다소 차이가 있다. 카카오맵 좌표 기준 -> 결국은 상세 주소로 안내한다.




💻 시도2

  • 현재 도로명 주소 검색 기반에서 키워드 검색도 가능하게 개선
  • 기존 카카오 api 요청 시, 쿼리 형태 그대로 가져와야 되는 줄 알았으나 애초에 브라우저에서 요청을 보낼 때는 인코딩 형태로 보내기 때문에 encode를 해야한다.
  • 그리고 나서 @RequestParam 으로 받으면 디코딩을 스프링에서 한다.




-> postman 처럼 uri를 만들어서 요청 -> encode를 제외해서 제대로 된 값을 받지 못함

  • 검색을 눌러도 아무런 반응이 없다. -> 왜냐하면 해당 api를 제대로 호출 하지 못하고 있기 때문



👉 list로 보여지는 로직 -> addressName , placeName 을 프론트에 보여줌

public class KeywordSearchService {

    private final KakaoKeywordSearchService kakaoKeywordSearchService;
    public List<List<String>> requestKeywordRandomWay(String query){
        if (ObjectUtils.isEmpty(query)) {
            return Collections.emptyList();  // 비어 있는 리스트 반환
        }

        KakaoApiResponseDto tourResponses = kakaoKeywordSearchService.requestAttractionKeywordSearch(query);
        // 주소명 로그로 체크
        List<String> tourAddressNames = tourResponses.getDocumentDtoList().stream()
                .map(DocumentDto::getAddressName)
                .collect(Collectors.toList());

        log.info("getDocumentDtoList addressNames : {} ", tourAddressNames.toString());

        // 장소명
        List<String> tourPlaceNames = tourResponses.getDocumentDtoList().stream()
                .map(DocumentDto::getPlaceName)
                .collect(Collectors.toList());
        log.info("getDocumentDtoList placeNames : {} ", tourPlaceNames.toString());

        // 이 두 리스트를 2개의 원소로 가지는 최종 리스트 생성
        List<List<String>> result = new ArrayList<>();
        result.add(tourPlaceNames);
        result.add(tourAddressNames);

        return result;
    }


👉 프론트 모달창 -> 리스트로 보여주기

 <div class="btn-group" role="group" aria-label="Default button group">
                        <button type='button' class='w-btn w-btn-indigo' id='all-random-search-origin'>도로명</button>
                        <button type='button' class='w-btn w-btn-indigo' id='all-random-search-keyword'>키워드</button>
                        <button type='button' class='w-btn w-btn-indigo' id='all-random-current-location'>현 위치
                        </button>
                    </div>

                    <!-- 키워드 모달 밖으로 이동 -->
                    <div id="keyword-modal" class="modal">
                        <div class="modal-content">
                            <span class="close-btn">×</span>
                            <input type="text" id="keyword-input" placeholder="키워드를 입력하세요">
                            <button type='button' id='keyword-search-btn'>검색</button>
                        </div>
                    </div>



    // 모달 창 열기
    $('#all-random-search-keyword').on('click', function() {
        $('#keyword-modal').show();
    });

    $('.close-btn').on('click', function() {
        $('#keyword-modal').hide();
    });

    // API 호출하여 키워드로 도로명 검색하기
    $('#keyword-search-btn').on('click', function() {
        var keyword = $('#keyword-input').val();
        searchKeyword(keyword);
    });

    function searchKeyword(keyword) {
        $.ajax({
            url: "/keyword-random-route",
            data: {
                query: keyword
            },
            success: function(response) {
                displayResults(response);
            },
            error: function(error) {
                console.error(error);
            }
        });
    }

    // 모달에 검색 결과 표시하기
    function displayResults(response) {
        var $results = $('<ul>');

        // 모달 내용 초기화
        $('.modal-content ul').remove();

        // 응답의 첫 번째 배열은 장소 이름, 두 번째 배열은 주소 이름입니다.
        for (var i = 0; i < response[0].length; i++) {
            (function(index) {
                var placeName = response[0][index];
                var addressName = response[1][index];
                var $li = $('<li>').text(placeName + ", " + addressName);
                $li.on('click', function() {
                    $('#all-random-originAddress').val(addressName);
                    $('#keyword-modal').hide();
                });
                $results.append($li);
            })(i);
        }
        $('.modal-content').append($results);
    }


결론

  • 키워드api를 활용해서 나온 주소의 uri를 눌렀을 때 나오는 상세 좌표와, 카테고리의 주소가 실제로는 같은 주소, 더 정확한 주소 가져올 수 없다.
  • 개선 사항 : 애매한 키워드 를 주소와 결합해서 좀 더 인지성 높은 주소로 저장
  • 개선 사항 : 현재 도로명 주소로만 검색해서 -> 길찾기 진행 중인 것을 사용자가 키워드를 입력했을 때, 해당 좌표로 변환가능(검색 기능 개선)

profile
디자인에서 개발자로

0개의 댓글