본문 바로가기
Programming/Android

[네이버 길찾기 API] Direction 5 API with Kotlin, Retrofit2

by soccerman 2020. 11. 20.
반응형

네이버 길찾기 구현 게시글을 찾기가 힘들어, 직접 구현하고 이를 공유한다.

 

일단 단순 네이버 Map(지도)를 화면에 띄웠다고, 가정하고 설명하겠다. 


순서

  • 네이버 Direction 5 api 사용 등록
  • Retrofit2 활용하여 통신을 통해 api 응답 바디 받아오기
  • 응답바디 parsing하여 GPS값들을 path_container에 넣고
  • path_container에 있는 값들을 path.coords에 넣고
  • 이를 화면에 띄우기

일단 네이버 길찾기 api를 활용하려면

NAVER AI api의 map 의 Directions 상품을 활용해야한다, 이는 REST API 방식으로만 제공한다. 따라서 Retrofit를 활용하여 통신하여 api값을 받아오면 한다.

 

www.ncloud.com/product/applicationService/maps

 

NAVER CLOUD PLATFORM

cloud computing services for corporations, IaaS, PaaS, SaaS, with Global region and Security Technology Certification

www.ncloud.com

위 링크로 들어가 하단의 이용신청 버튼을 누른다.

 

Direction 5와 Direction 15가 있을 것인데 이 둘은 경유지 추가 한도만 차이가 있을뿐 비슷한 api이다. 따라서 Direction5 이용 신청을 한다.


retrofit dependancy 등록

 


https://api.ncloud-docs.com/docs/ai-naver-mapsdirections-driving

 

driving - Directions 5

쿠키 제공 동의 당사는 고객님의 브라우징 기반 정보를 바탕으로 관련 정보 및 광고 제공을 위하여 지식 기반 쿠키를 사용합니다.

api.ncloud-docs.com

 

Direction5 api 참조서 하단의 응답바디를 보면

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
{
    "code": 0,
    "message": "길찾기를 성공하였습니다.",
    "currentDateTime": "2018-12-21T14:45:34",
    "route": {
        "trafast": [
            {
                "summary": {
                    "start": {
                        "location": [
                            127.1058342,
                            37.3597078
                        ]
                    },
                    "goal": {
                        "location": [
                            129.0759853,
                            35.1794697
                        ],
                        "dir": 2
                    },
                    "distance": 382403,
                    "duration": 15372873,
                    "bbox": [
                        [
                            127.0833901,
                            35.1793188
                        ],
                        [
                            129.0817364,
                            37.3599059
                        ]
                    ],
                    "tollFare": 24500,
                    "taxiFare": 319900,
                    "fuelPrice": 46027
                },
                "path": [
                    [
                        127.1059968,
                        37.3597093
                    ],
 
                    ....
 
                    [
                        129.0764276,
                        35.1795108
                    ],
                    [
                        129.0762855,
                        35.1793188
                    ]
                ],
                "section": [
                    {
                        "pointIndex": 654,
                        "pointCount": 358,
                        "distance": 22495,
                        "name": "죽양대로",
                        "congestion": 1,
                        "speed": 60
                    },
                    {
                        "pointIndex": 3059,
                        "pointCount": 565,
                        "distance": 59030,
                        "name": "낙동대로",
                        "congestion": 1,
                        "speed": 89
                    },
                    {
                        "pointIndex": 4708,
                        "pointCount": 433,
                        "distance": 23385,
                        "name": "새마을로",
                        "congestion": 1,
                        "speed": 66
                    }
                ],
                "guide": [
                    {
                        "pointIndex": 1,
                        "type": 3,
                        "instructions": "정자일로1사거리에서 '성남대로' 방면으로 우회전",
                        "distance": 21,
                        "duration": 4725
                    },
                    {
                        "pointIndex": 8,
                        "type": 3,
                        "instructions": "불정교사거리에서 '수원·용인, 미금역' 방면으로 우회전",
                        "distance": 186,
                        "duration": 42914
                    },
 
                     ....
 
                    {
                        "pointIndex": 6824,
                        "type": 14,
                        "instructions": "연산교차로에서 '서면교차로, 시청·경찰청' 방면으로 오른쪽 1시 방향",
                        "distance": 910,
                        "duration": 125240
                    },
                    {
                        "pointIndex": 6842,
                        "type": 88,
                        "instructions": "목적지",
                        "distance": 895,
                        "duration": 111333
                    }
                ]
            }
        ]
    }
}
 
cs

이와 같다.

 

여기서 route => trafast => path 안에 있는 위도 경도 리스트가 경로를 의미한다.

api 호출시 default값은 trafast(빠른길)가 아니라 traoptimal이다. 따라서 이를 데이터 클래스에 반영한다.

 

api 응답 바디를 받을 데이터클래스를 정의하고. (ResultPath.kt)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
data class ResultPath(
    val route : Result_trackoption,
    val message : String,
    val code : Int
)
data class Result_trackoption(
    val traoptimal : List<Result_path>
)
data class Result_path(
    val summary : Result_distance,
    val path : List<List<Double>>
)
data class Result_distance(
    val distance : Int
)
cs

json 응답 형식 이용해 데이터 클래스를 자동 생성해주는 사이트

http://pojo.sodhanalibrary.com/


api 요청을 보낼 쿼리를 작성한다. (NaverAPI)

1
2
3
4
5
6
7
8
9
10
interface NaverAPI{
    @GET("v1/driving")
    fun getPath(
        @Header("X-NCP-APIGW-API-KEY-ID") apiKeyID: String,
        @Header("X-NCP-APIGW-API-KEY") apiKey: String,
        @Query("start") start: String,
        @Query("goal") goal: String,
    ): Call<ResultPath>
 
}
cs

이제 아래와 같이 Mainactivity에서 Retrofit 객체를 생성하고 일련의 작업을 거쳐 경로를 띄운다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
        val APIKEY_ID = "본인의 APIKEI_ID를 여기다 적으세요"
        val APIKEY = "본인의 APIKEY를 여기다 적으세요"
        //레트로핏 객체 생성
        val retrofit = Retrofit.Builder().
                baseUrl("https://naveropenapi.apigw.ntruss.com/map-direction/").
                addConverterFactory(GsonConverterFactory.create()).
                build()
 
        val api = retrofit.create(NaverAPI::class.java)
        //근처에서 길찾기
        val callgetPath = api.getPath(APIKEY_ID, APIKEY,"129.089441, 35.231100""129.084454, 35.228982")
 
        callgetPath.enqueue(object : Callback<ResultPath>{
            override fun onResponse(
                call: Call<ResultPath>,
                response: Response<ResultPath>
            ) {
                path_cords_list = response.body()?.route?.traoptimal
                //경로 그리기 응답바디가 List<List<Double>> 이라서 2중 for문 썼음
                val path = PathOverlay()
                //MutableList에 add 기능 쓰기 위해 더미 원소 하나 넣어둠
                val path_container : MutableList<LatLng>= mutableListOf(LatLng(0.1,0.1))
                for(path_cords in path_cords_list!!){
                    for(path_cords_xy in path_cords?.path){
                        //구한 경로를 하나씩 path_container에 추가해줌
                        path_container?.add(LatLng(path_cords_xy[1], path_cords_xy[0]))
                    }
                }
                //더미원소 드랍후 path.coords에 path들을 넣어줌.
                path.coords = path_container?.drop(1)!!
                path.color = Color.RED
                path.map = naverMap
 
                //경로 시작점으로 화면 이동
                if(path.coords != null) {
                    val cameraUpdate = CameraUpdate.scrollTo(path.coords[0]!!)
                        .animate(CameraAnimation.Fly, 3000)
                    mNaverMap!!.moveCamera(cameraUpdate)
 
                    Toast.makeText(this@MainActivity, "경로 안내가 시작됩니다.", Toast.LENGTH_SHORT).show()
                }
            }

cs
 
 
 

 

 

 

 

참고자료

navermaps.github.io/android-map-sdk/guide-ko/5-7.html

 

경로선과 화살표 · 네이버 지도 안드로이드 SDK

No results matching ""

navermaps.github.io

 

자유롭게 댓글 달아주시면 답변드리겠습니다.

반응형

댓글