본문 바로가기
Vue.js

최단거리 구하기(1)

by 캡틴노랑이 2023. 3. 22.
반응형

테스트 환경

vue.js : 3.2.13

 

 

네이버 맵을 기반으로 하여서 최적 해를 구하는 코드입니다. 

주소를 gps좌표 변환 api도 네이버를 이용하였습니다. 

네이버랑 아무 관계없고.. 단지.. 그냥... 네이버 활용하였습니다. 

최단거리(최적 해)를 구하는 것이... 결론만 말하면.. 

모든 지점간 거리를 알고 있어야 하고, AI는 아무 것도 모르지만... 

AI도 내가 생각한 것과 동일하게 각 지점간 모든 거리를 알고 계산하는게 아닌가 싶네요. 

혹시 아니라고 하시는 분들 댓글 남겨주시면, 공부 하겠습니다. 

아무리 생각해도 이건... 다 알지 않고서는 어디가 최단거리인지 알수가 없네요. 

지금은 직선 거리로 최단거리를 코드를 알려드리지만, 

이후에 추가 되는 글에는 네이버 네비게이션 상의 최단 거리를 구하는 코드로 올라갈 예정입니다. 

물론, 네이버 뿐아니라, T맵도 동일하게 가능할 것으로 보입니다. 

 

아래 동영상 설명.

1. 시작 주소 저장 버튼 클릭 -> 시작 주소를 시작점으로 나머지 주소를 검색.

2.목적지 주소 검색 버튼 클릭 -> 목적지 주소의 GPS상 좌표를 구해야 하기 때문에 시작 주소와 구분함

   *이유: 비동기 호출이라.. 순서가 달라짐. 먼저 보냈다고 해서 먼저 오지 않음.

3. 경로 조회 버튼 클릭-> 최단 거리를 구하는 로직을 실행함.

   *목적지 주소 검색 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
<template>
    <table>
        <tr>
            <td>
                시작주소
            </td>
            <td>
                <DxTextBox placeholder="시작주소" :value="addressStart"  :width="500" />
            </td>
        </tr>
        <tr>
            <td>
                목적지 주소 목록
            </td>
            <td>
                <DxTextBox placeholder="주소" :value="addressList"  :width="500" />
            </td>
        </tr>
    </table>
    <DxButton  text="시작 주소 저장" :width="150" styling-mode="contained" type="default" @click="onClickStartAddressSearch()" />
    <DxButton  text="목적지 주소 검색" :width="150" styling-mode="contained" type="default" @click="onAddressListSearch()" />
    <DxButton  text="경로 조회" :width="100" styling-mode="contained" type="default" @click="onCalc()" />
 
    <table>
        <tr>
            <td>
                <div id="map" style="width:600px;height:600px"></div>
            </td>
            <td style="vertical-align:text-top;">
                <span style="display: inline-block;">
                    <DxDataGrid
                        id="gridContainer"
                        :data-source="orderByRanking"
                        :column-auto-width="false"
                        :show-borders="false"
                        :row-alternation-enabled="true"
                        key-expr="Rank"
                        ref="grid"
                        @row-click="onGridRowClick"
                        >
                        <DxColumnChooser :enabled="false"/><!-- 컬럼 감추기, 선택해서 보이게 우상단에 아이콘 하나 생김 -->
                        <DxColumnFixing :enabled="false"/> <!--행고정시 다음 옵션 필수   :column-auto-width="false"  :fixed="true"  --->
                        <DxScrolling mode="infinite"/><!--무한 스크롤-->
                        <DxColumn :width="80" data-field="Rank"  :fixed="true" caption="Rank" data-type="int" alignment="center" :allow-sorting="false" />
                        <DxColumn :width="150" data-field="route" caption="경로" data-type="string" alignment="center" :allow-sorting="false" />
                        <DxColumn :width="100" data-field="distance" caption="거리" data-type="string" alignment="right" :allow-sorting="false" />
                    </DxDataGrid>
                </span>
                <span style="display: inline-block;">
                    <ul>
                        <li v-for="item in markerLst" v-bind:key="item">
                            {{ item.dong }} - {{ item.dongNo }}
                        </li>
                    </ul>
                </span>
            </td>
        </tr>
        <tr>
            <td>
                <ul>
                    <li v-for="item in markerDistance" v-bind:key="item">
                        start:{{ item.s }} - end:{{ item.e }} -거리: {{ item.distance }}
                    </li>
                </ul>
 
                <ul>
                    <li v-for=" (item, index) in orderByRanking" v-bind:key="item" @click="onDrawRouteLine(index)">
                        {{ index + 1 }} -
                        route:
                        <span v-for = "r in item.route" v-bind:key="r">
                            {{ r }}
                        </span>
                        , distance:{{ item.distance }}
                    </li>
                </ul>
            </td>
            <td>
                <ul>
                    <li v-for="item in routeDepth" v-bind:key="item">
                        route:
                        <span v-for = "r in item.route" v-bind:key="r">
                            {{ r }}
                        </span>
                        level: {{ item.level }} - distance:{{ item.distance }}
                    </li>
                </ul>
            </td>
        </tr>
    </table>
 
 
 
</template>
<script>
    import { DxButton } from 'devextreme-vue/button'
    import { DxTextBox } from "devextreme-vue/text-box"
    import { DxDataGrid, DxColumn, DxColumnChooser, DxScrolling
        //DxColumnFixing,
        //DxScrolling
    } from 'devextreme-vue/data-grid'
 
    var nMap
 
    export default {
        name: 'NaverMap2'
        , components: {
            DxButton
            , DxTextBox
            , DxDataGrid
            , DxColumn
            , DxColumnChooser
            , DxScrolling
        }
        , data() {
            return {
                markerLst : []// {'dong' : dong, 'dongNo' : dongNo, 'road' : road,'roadNo' : roadNo, 'x' : x, 'y' : y }
                , markerDistance :[]//{s:0, e:1, distance:3}
                // {"s": 0,"e": 1,"distance": 1.3234723327641063e-8},
                // {"s": 0,"e": 2,"distance": 2.066463741484345e-8},
                // {"s": 0,"e": 3,"distance": 6.739547006524355e-8},
                // {"s": 0,"e": 4,"distance": 3.832084574747789e-8},
                , routeDepth :[]//{route:'0,1,2,3', level: 3, distance:3}
                //recursionCnt : 4 //시작점인 0을 빼면 4계층
                //  {"route":[0,1,2,3,4],"level":4,"distance":"7.93"}
                // ,{"route":[0,1,2,4,3],"level":4,"distance":"6.33"}
                // ,{"route":[0,1,3,2,4],"level":4,"distance":"5.79"}
                , orderByRanking : []
                // {"route":[0,1,3,4,2],"level":4,"distance":"5.27"}
                // ,{"route":[0,2,4,3,1],"level":4,"distance":"5.50"}
                , routeLine : undefined
 
                //주소 목록
                , addressList :'상록구 성포동 590,단원구 고잔동 767,단원구 고잔동 702,상록구 사동 1585,상록구 이동 693-4' //55개
                , addressStart :'단원구 초지동 741'
                , addressEnd :'상록구 이동 574-1'
            }
        }
        , mounted() {
 
            this.initMap()
        }
        , methods: {
            initMap()
            {
                var mapOptions = {
 
                      scaleControl: true           //우하단 축척
                    , logoControl: true            //네이버 로고 뭔지 모르겠음.
                    , mapDataControl: true         //좌하단 네이버 로고
                    , mapTypeControl: true         //지도 유형 컨트롤
                    , zoom: 14
                    , zoomControl: true            //줌 컨트롤
                    // , zoomControlOptions: {     //줌 컨트롤 스타일
                    //     style: naver.maps.ZoomControlStyle.SMALL,
                    //     position: naver.maps.Position.TOP_RIGHT
                    //     }                        //주석 풀면 우측에 +-로만 생김
                    , maxZoom : 19                  //최대 줌 레벨
                    , minZoom :6                    //최소 줌 레벨
                    , disableDoubleClickZoom : false//더블 클릭해 지도를 확대하는 기능의 사용 여부
                    , mapTypeId: naver.maps.MapTypeId.NORMAL//NORMAL SATELLITE HYBRID  지도의 초기 지도 유형 id입니다.
                    , keyboardShortcuts : true      //키보드 방향 키를 이용한 지도 이동(패닝) 허용 여부입니다.
                }
 
                nMap = new naver.maps.Map('map', mapOptions)
 
                naver.maps.Event.addListener(nMap, 'click', this.mapClick)
                naver.maps.Event.addListener(nMap, 'rightclick', this.mapRightClick)
 
                nMap.setCenter(new naver.maps.LatLng(37.3089449, 126.8367496))
            }
 
            //#region event
            , onCalc()
            {
                this.PtoPDistance();
                this.drawMarker();
                this.totalDistance();
                this.ranking();
            }
 
            ,onClickStartAddressSearch()
            {
                this.callNaverAddressService(this.addressStart)//시작 주소
            }
 
            //주소 목록 검색
            ,onAddressListSearch()
            {
                //1.주소 분할
                var addrList = this.addressList.split(',')
 
                //2.리스트 추가
                for(var i=0; i < addrList.length; i++)
                    this.callNaverAddressService(addrList[i]);//시작 주소
 
                //4.마지막 주소는 별도 관리 일단 추후에 생각해 보기.
            }
 
 
            //#region map event
            , mapClick(e)
            {
                alert('현좌표(left click)' + e.coord.x + '-' + e.coord.y)
            }
 
            , mapRightClick(e)
            {
                naver.maps.Service.reverseGeocode({
                    coords: new naver.maps.LatLng(e.coord.y, e.coord.x),
                }, function(status, response) {
                    if (status !== naver.maps.Service.Status.OK) {
                        return alert('Something wrong!');
                    }
 
                    var result = response.v2 // 검색 결과의 컨테이너
                    //var items = result.results // 검색 결과의 배열
                    //var address = result.address // 검색 결과로 만든 주소
 
                    alert('현주소(rightClick) ' + result.address.jibunAddress)
 
                });
            }
            //#endregion
 
            , onGridRowClick(e)
            {
                //alert(e); //e.rowIndex
                this.drawRouteLine(e.rowIndex);
            }
            //#endregion
 
 
            //#region function
            , drawMarker()
            {
 
                //무료 아이콘
                //https://www.iconfinder.com/search?q=dog&price=free
                for(var arr in this.markerLst)
                {
                     //이미지 마커
                    var imageMarkerOptions = {
                        position: new naver.maps.LatLng(this.markerLst[arr].y, this.markerLst[arr].x)
                        , map: nMap
                        , icon: {
                                url: require('@/images/' + (arr == 0 ? 'flags_4.svg' : 'flags_1.svg'))
                                //, size: new naver.maps.Size(24, 24)
                                //, origin: new naver.maps.Point(0, 0)
                                //, anchor: new naver.maps.Point(0, 0)
                            }
                        };
 
                    var imageMarker = new naver.maps.Marker(imageMarkerOptions)
 
                    //marker event
                    naver.maps.Event.addListener(imageMarker, 'click', this.markerClick)
                    // 이벤트는 폴리곤, 마커 등 각각 지원하는게 있고, 안하는 것이 있음. api 확인 할 것
                    // 아래는 전체 이벤트
                    // mousedown, mouseup, click, dblclick, rightclick, mouseover, mouseout, mousemove
                    // dragstart, drag, dragend
                    // touchstart, touchmove, touchend, pinchstart, pinch, pinchend, tap, longtap, twofingertap, doubletap
 
                }
            }
 
            //2점간 거리 계간
            , PtoPDistance()
            {
                var dist = 0;
                for(var i= 0; i < this.markerLst.length; i++ )
                {
                    for(var j = i +1; j < this.markerLst.length; j++ )
                    {
                        dist = this.distance(this.markerLst[i].x, this.markerLst[i].y, this.markerLst[j].x, this.markerLst[j].y, 'KM');
                        this.markerDistance.push({'s': i, 'e': j, 'distance' : dist.toFixed(2) })
                    }
                }
 
                console.log(this.markerDistance)
            }
 
            /**
             * 두 지점간의 거리 계산
             *
             * @param lat1 지점 1 위도
             * @param lon1 지점 1 경도
             * @param lat2 지점 2 위도
             * @param lon2 지점 2 경도
             * @param unit 거리 표출단위
             * @return
             */
            , distance(lat1, lon1, lat2, lon2, unit)
            {
                var theta = lon1 - lon2;
                var dist = Math.sin(this.deg2rad(lat1))* Math.sin(this.deg2rad(lat2)) + Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * Math.cos(this.deg2rad(theta));
 
                dist = Math.acos(dist);
                dist = this.rad2deg(dist);
                dist = dist * 60 * 1.1515;
 
                if (unit == "KM") {
                    dist = dist * 1.609344;
                } else if(unit == "M"){
                    dist = dist * 1609.344;
                }
 
                return dist;
            }
 
            // This function converts decimal degrees to radians
            , deg2rad(deg)
            {
                return (deg * Math.PI / 180.0);
            }
 
            // This function converts radians to decimal degrees
            , rad2deg(rad) {
                return (rad * 180 / Math.PI);
            }
 
            //최단 거리 구하기
            , totalDistance()
            {
                var data;
                var depthLevel = 0;
                var route;
                var distance = 0;
 
                //기준점(시작점) 0에서 시작
                for(var i= 1;  i < this.markerLst.length; i++)
                {
                    //재귀를 돌아야 됨.
                    depthLevel = 1;
                    route = new Array();
                    route.push(0);
                    route.push(i);
 
                    //거리계산
                    for(var j = 0; j < this.markerDistance.length; j++)
                    {
                        if((0 == this.markerDistance[j].s && i == this.markerDistance[j].e))
                        {
                            distance = Number(this.markerDistance[j].distance);
                        }
                    }
 
                    data = {'route': route, 'level' : depthLevel + 1, 'distance' : distance};
                    this.recursionRoute(data, depthLevel);
                }
            }
 
            , recursionRoute(data, depthLevel)
            {
                var rData
                var level = depthLevel + 1
                var s, e
 
                if(level < this.markerLst.length)
                {
                    for(var i= 1;  i < this.markerLst.length; i++)
                    {
                        if(!data.route.includes(i))//포함되어 있는지 체크
                        {
                            rData = JSON.parse(JSON.stringify(data))//객체 복사 문제 생김.
                            //rData = data
                            rData.route.push(i)
                            rData.level = level
 
                            //거리계산
                            //2가지 경우, se, e,s로 해서 더할 것.
                            s = rData.route[rData.route.length-2]//-1로 할 경우 route.push(i) 앞에 있어야 됨.
                            e = i
                            for(var j = 0; j < this.markerDistance.length; j++)
                            {
                                if((s == this.markerDistance[j].s && e == this.markerDistance[j].e) || (e == this.markerDistance[j].s && s == this.markerDistance[j].e))
                                {
                                    //이렇게 해주면,,, 일부 데이터가 소수점 이하 16자리까지 나옴. 이유는 모르겠음.
                                    //5.7700000000000005 toFixed(2)를 해주면 정상적으로 나옴. 실 데이터는 문제가 없음.??? 왜지?? 연산 오류?
                                    //rData.distance = (Number( rData.distance) + Number(this.markerDistance[j].distance))
                                    rData.distance = (Number( rData.distance) + Number(this.markerDistance[j].distance)).toFixed(2)
                                    //console.log(rData.distance)
                                }
                            }
 
                            this.recursionRoute(rData, level)
 
                            //if(level == this.markerLst - 1 ){
                                if(level == this.markerLst.length -1 ){
                                //console.log(rData)
                                this.routeDepth.push(rData)
                            }
                        }
                    }
                }
            }
 
            //swap
            , ranking()
            {
                var data = JSON.parse(JSON.stringify(this.routeDepth))
 
                data.sort(function(a,b) {
 
                    //a-b는 오름차순
                    //b-a는 내림차순
                    return parseFloat(a.distance) - parseFloat(b.distance);
                });
 
 
                for(var i = 0; i< data.length; i++)
                    data[i].Rank = i + 1;
 
                this.orderByRanking = data;
            }
 
            //draw route line
            , drawRouteLine(index)
            {
                var routeRow = this.orderByRanking[index];
                var polyLinePath= [];
 
                for(var i = 0; i< routeRow.route.length; i++)
                    polyLinePath.push(new naver.maps.LatLng(this.markerLst[routeRow.route[i]].y, this.markerLst[routeRow.route[i]].x));
 
                if(this.routeLine != undefined)
                    this.routeLine.setMap(null);
 
                //routeLine
                var polyline = new naver.maps.Polyline({
                    path: polyLinePath,
                    strokeColor: '#00CA00',
                    strokeOpacity: 0.8,
                    strokeWeight: 3,
                    zIndex: 1,
                    clickable: true,
                    map: nMap
                });
 
                this.routeLine = polyline
            }
            //#endregion
 
            //#region service
 
            //주소로 좌표 불러오기
            ,callNaverAddressService(address)
            {
                var that = this;
 
                naver.maps.Service.geocode({query:address},function(status, response){
 
                    if (status !== naver.maps.Service.Status.OK)
                        return alert('Something wrong!');
 
                    var dong = response.v2.addresses[0].addressElements[2].longName;//동
                    var dongNo = response.v2.addresses[0].addressElements[7].longName;//지번
                    var road = response.v2.addresses[0].addressElements[4].longName;//도로명 주소
                    var roadNo = response.v2.addresses[0].addressElements[5].longName;//도로명 지번
                    var x = response.v2.addresses[0].x;//126.8620435
                    var y = response.v2.addresses[0].y;//37.3047594
 
 
                    //주소 목록은 저장{dong:'', dongNo:'', road:'',roadNo='', x:, y: }
                    that.markerLst.push({'dong' : dong, 'dongNo' : dongNo, 'road' : road,'roadNo' : roadNo, 'x' : x, 'y' : y })
 
                })
            }
 
            //#endregion
        }
    }
 
</script>
<style scoped>
#gridContainer {
  height: 600px;
  width:400px;
}
</style>

 

네이버 맵에서 실제 경로(네비게이션 상 경로)로 구현한 코드는 추후 올라 감. 

반응형