[Spring Boot] Tmap API를 이용한 Geocoding - 위치 정보를 좌표로 반환하기

2024. 1. 29. 00:42·웹 개발/Spring

Tmap API의 GeoCoding을 사용해 볼 것이다.
 

 

Guide | T MAP API

tmapapi.sktelecom.com

 
먼저 Tmap의 서비스에 가입하여 appKey를 발급받아야 한다.
이 부분은 생략하겠다.
 


 
위 링크를 들어가면 볼 수 있는 화면이다. 여기서 필요한 정보들을 참고하여 사용하면 된다.
 
 
GeoController

@RestController
@RequestMapping("/geocode")
public class GeoController {
    @Autowired
    private GeoService geoService;

    @GetMapping("/convert")
    public TmapResponseDto convertAddressToCoordinates(@RequestBody TmapRequestDto tmapRequestDto) {
        TmapResponseDto coordinates = geoService.getCoordinates(tmapRequestDto);
        return coordinates;
    }
}

 
Geocoding의 메소드 타입은 Get이기 때문에, GetMapping을 사용한다.
return 타입은 DTO 타입으로 했다.
 
 
 
TmapRequestDto

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class TmapRequestDto {

    private String city_do;         // 시도
    private String gu_gun;          // 구군
    private String dong;            // 동
    private String bunji;           // 번지
    private String detailAddress;   // 상세주소
}

 
 
 
TmapResponseDto

@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
@Data
public class TmapResponseDto {
    private CoordinateInfo coordinateInfo;

    @Data
    public static class CoordinateInfo {
        private String coordType;
        private String addressFlag;
        private String matchFlag;
        private String lat;
        private String lon;
        private String city_do;
        private String gu_gun;
        private String eup_myun;
        private String legalDong;
        private String legalDongCode;
        private String adminDong;
        private String adminDongCode;
        private String ri;
        private String bunji;
        private String newMatchFlag;
        private String newLat;
        private String newLon;
        private String newRoadName;
        private String newBuildngIndex;
        private String newBuildngName;
        private String newBuildngCateName;
        private String remainder;
    }
}

 
ResponseDto는 Tmap에서 제공할 수 있는 모든 Response Parameter를 넣었다.
 
 
 
GeoService

@Slf4j
@RequiredArgsConstructor
@Service
public class GeoService {

    private final RestTemplate restTemplate;
    @Value("${tmap-geocoding.appKey}")
    private String tmapApiKey;

    public TmapResponseDto getCoordinates(TmapRequestDto tmapRequestDto) {

        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        String body = gson.toJson(tmapRequestDto);

        // TMap API 요청 URL 작성
        String url = "https://apis.openapi.sk.com/tmap/geo/geocoding?" +
                "version=1" +
                "&city_do=" + tmapRequestDto.getCity_do() +
                "&gu_gun=" + tmapRequestDto.getGu_gun() +
                "&dong=" + tmapRequestDto.getDong() +
                "&bunji=" + tmapRequestDto.getBunji() +
                "&detailAddress=" + tmapRequestDto.getDetailAddress() +
                "&addressFlag=F01" +
                "&coordType=WGS84GEO" +
                "&appKey=" + tmapApiKey;

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");


        HttpEntity<String> request = new HttpEntity<>(headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);

        String responseBody = responseEntity.getBody();

        // responseBody를 파싱하여 TmapResponseDto 객체로 변환
        TmapResponseDto tmapResponseDto = gson.fromJson(responseBody, TmapResponseDto.class);

        // 좌표 정보 추출
        System.out.println("위도 : " + tmapResponseDto.getCoordinateInfo().getLat() + "\n" +
                "경도 : " + tmapResponseDto.getCoordinateInfo().getLon());

        return tmapResponseDto;

    }
}

 
yml 파일에 작성한 TmapApiKey를 변수에 담아 활용한다.
Geocoding 기본정보에 있는 Resource URI를 참고하여 URL을 작성한다.
이후 파싱하여 DTO 객체로 변환하고 좌표 정보를 추출하면 된다.
 


 
 
이제 잘 작동되는지 포스트맨으로 테스트 해보자.
 

 
GET 방식으로 설정하고 localhost:포트번호/controller 주소를 적으면 된다.
이후 RequestDto의 변수를 JSON 파라미터 형식으로 입력해야 한다.
 
 

 
요청 결과로 lat(위도)과 lon(경도)이 잘 반환된 것을 볼 수 있다.
 

console 창

'웹 개발 > Spring' 카테고리의 다른 글

Spring 전자정부프레임워크 3.9 > 4.0 마이그레이션  (0) 2025.07.30
Spring 컨트롤러 이름 변경 후 org.springframework.beans.factory.BeanCreationException 에러 해결 방법  (0) 2024.11.19
Spring Boot 프로젝트 생성하기 - 이클립스(Eclipse), 인텔리제이(Intellij)  (0) 2024.11.13
[Spring Boot] 파일 업로드와 섬네일 처리  (0) 2023.10.09
[Spring Boot] CoolSMS API를 이용한 휴대폰 본인인증  (0) 2023.10.09
'웹 개발/Spring' 카테고리의 다른 글
  • Spring 컨트롤러 이름 변경 후 org.springframework.beans.factory.BeanCreationException 에러 해결 방법
  • Spring Boot 프로젝트 생성하기 - 이클립스(Eclipse), 인텔리제이(Intellij)
  • [Spring Boot] 파일 업로드와 섬네일 처리
  • [Spring Boot] CoolSMS API를 이용한 휴대폰 본인인증
오은이
오은이
  • 오은이
    오은이 하우스
    오은이
  • 전체
    오늘
    어제
    • 분류 전체보기 (81)
      • 일기 (2)
      • Python (1)
      • Java (4)
      • CS (2)
      • 코딩테스트 (26)
        • 백준 (25)
        • 프로그래머스 (1)
      • 웹 개발 (17)
        • Spring (6)
        • JavaScript (3)
        • WebSquare (5)
        • React (3)
      • DB (5)
        • MySQL (4)
        • Oracle (1)
      • 서버&인프라 (18)
        • Server (5)
        • Cloud (12)
        • Linux (1)
      • 자격증 (6)
        • 정보처리기사 (1)
        • AICE (5)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • GitHub
  • 공지사항

  • 인기 글

  • 태그

    Associate
    클라우드
    AI
    백준
    Java
    톰캣
    리액트
    자바
    react
    웹스퀘어
    AICE
    docker
    MySQL
    AICE Associate
    머신러닝
    docker배포
    dockerspring
    Apache
    Spring
    클라우드 배포
    티스토리챌린지
    tomcat
    오블완
    EC2
    백준자바
    cloud DB
    SpringBoot
    db
    websquare
    알고리즘
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
오은이
[Spring Boot] Tmap API를 이용한 Geocoding - 위치 정보를 좌표로 반환하기
상단으로

티스토리툴바