-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlmn-core.js
More file actions
1636 lines (1394 loc) · 52.5 KB
/
Copy pathlmn-core.js
File metadata and controls
1636 lines (1394 loc) · 52.5 KB
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function () {
'use strict';
const DEFAULT_CENTER = { lat: 37.5665, lon: 126.9780 };
const SEARCH_TIMEOUT_MS = 6000;
const OVERPASS_TIMEOUT_MS = 10000;
const NEARBY_RADIUS_M = 1500;
const state = {
map: null,
currentPosition: null,
startPoint: null,
destination: null,
userMarker: null,
startMarker: null,
destinationMarker: null,
nearbyLayer: null,
nearbyLast: [],
nearbyRadiusM: 1500,
routeLayer: null,
routeMode: 'driving',
};
const coordsEl = document.getElementById('coords-display');
const statusEl = document.getElementById('status-message');
const startInputEl = document.getElementById('start-input');
const inputEl = document.getElementById('destination-input');
const directionsBtn = document.getElementById('directions-btn');
const mapEl = document.getElementById('map');
const networkBadgeEl = document.getElementById('network-badge');
const recentSearchListEl = document.getElementById('recent-search-list');
const clearRecentBtn = document.getElementById('clear-recent-btn');
const saveFavoriteBtn = document.getElementById('save-favorite-btn');
const routeSummaryEl = document.getElementById('route-summary');
const routeFareSummaryEl = document.getElementById('route-fare-summary');
const routeModeButtons = document.querySelectorAll('[data-route-mode]');
const routeComboSelectEl = document.getElementById('route-combo-select');
const comboRouteBtn = document.getElementById('combo-route-btn');
const comboSummaryEl = document.getElementById('combo-summary');
const menuToggleBtn = document.getElementById('menu-toggle-btn');
const menuCloseBtn = document.getElementById('menu-close-btn');
const favoritesListEl = document.getElementById('favorites-list');
const clearFavoritesBtn = document.getElementById('clear-favorites-btn');
const toggleThemeBtn = document.getElementById('toggle-theme-btn');
const resetMapBtn = document.getElementById('reset-map-btn');
const copyCoordsBtn = document.getElementById('copy-coords-btn');
const shareDestinationBtn = document.getElementById('share-destination-btn');
const nearbyRadiusRange = document.getElementById('nearby-radius-range');
const nearbyRadiusLabel = document.getElementById('nearby-radius-label');
const exportDataBtn = document.getElementById('export-data-btn');
const importDataBtn = document.getElementById('import-data-btn');
const importDataInput = document.getElementById('import-data-input');
const STORAGE_KEYS = {
RECENT: 'lmn-recent-searches',
FAVORITES: 'lmn-favorites',
START: 'lmn-start-point',
DESTINATION: 'lmn-last-destination',
POSITION: 'lmn-last-position',
VIEW: 'lmn-last-view',
THEME: 'lmn-theme-mode',
SETTINGS: 'lmn-settings',
};
function loadJson(key, fallback) {
try {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : fallback;
} catch {
return fallback;
}
}
function saveJson(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// Ignore storage quota errors for MVP.
}
}
function clamp(n, min, max) {
return Math.max(min, Math.min(max, n));
}
function applyTheme(mode) {
const root = document.documentElement;
if (!root) {
return;
}
const dark = mode === 'dark';
root.classList.toggle('dark', dark);
root.classList.toggle('light', !dark);
saveJson(STORAGE_KEYS.THEME, mode);
if (toggleThemeBtn) {
toggleThemeBtn.textContent = dark ? '라이트' : '다크';
}
}
function toggleTheme() {
const current = loadJson(STORAGE_KEYS.THEME, 'light');
applyTheme(current === 'dark' ? 'light' : 'dark');
}
function updateNetworkBadge() {
if (!networkBadgeEl) {
return;
}
const online = navigator.onLine;
networkBadgeEl.textContent = online ? '온라인' : '오프라인';
networkBadgeEl.classList.remove('bg-green-100', 'text-green-700', 'bg-amber-100', 'text-amber-700');
networkBadgeEl.classList.add(online ? 'bg-green-100' : 'bg-amber-100');
networkBadgeEl.classList.add(online ? 'text-green-700' : 'text-amber-700');
}
function renderRecentSearches() {
if (!recentSearchListEl) {
return;
}
const recents = loadJson(STORAGE_KEYS.RECENT, []);
recentSearchListEl.innerHTML = '';
recents.slice(0, 8).forEach(function (keyword) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'text-[11px] px-2 py-1 rounded-full border border-outline-variant whitespace-nowrap';
button.textContent = keyword;
button.addEventListener('click', function () {
if (inputEl) {
inputEl.value = keyword;
}
searchDestination();
});
recentSearchListEl.appendChild(button);
});
}
function renderFavorites() {
if (!favoritesListEl) {
return;
}
const favorites = loadJson(STORAGE_KEYS.FAVORITES, []);
favoritesListEl.innerHTML = '';
if (favorites.length === 0) {
const empty = document.createElement('p');
empty.className = 'text-[11px] text-on-surface-variant';
empty.textContent = '저장된 목적지가 없습니다.';
favoritesListEl.appendChild(empty);
return;
}
favorites.slice(0, 6).forEach(function (item, index) {
const row = document.createElement('div');
row.className = 'flex items-center gap-2';
const openBtn = document.createElement('button');
openBtn.type = 'button';
openBtn.className = 'flex-1 text-left text-[11px] px-2 py-1 rounded-full border border-outline-variant truncate';
openBtn.textContent = item.label;
openBtn.title = item.label;
openBtn.addEventListener('click', function () {
const lat = Number(item.lat);
const lon = Number(item.lon);
if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
return;
}
state.destination = { lat: lat, lon: lon, label: item.label || '저장 목적지' };
clearRoute();
setRouteSummary('목적지가 변경되었습니다. 내부 길찾기를 눌러 경로를 계산하세요.');
setFareSummary('예상 요금: -');
setDestinationMarker(lat, lon, state.destination.label);
updateDirectionsState();
const map = ensureMap();
if (map) {
map.setView([lat, lon], Math.max(map.getZoom(), 15));
}
saveJson(STORAGE_KEYS.DESTINATION, state.destination);
setStatus('저장된 목적지를 불러왔습니다.', 'success');
});
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.className = 'text-[11px] px-2 py-1 rounded-full bg-error-container text-on-error-container';
delBtn.textContent = '삭제';
delBtn.addEventListener('click', function () {
const next = loadJson(STORAGE_KEYS.FAVORITES, []).filter(function (_x, i) {
return i !== index;
});
saveJson(STORAGE_KEYS.FAVORITES, next);
renderFavorites();
});
row.appendChild(openBtn);
row.appendChild(delBtn);
favoritesListEl.appendChild(row);
});
}
function pushRecentSearch(keyword) {
if (!keyword) {
return;
}
const recents = loadJson(STORAGE_KEYS.RECENT, []);
const next = [keyword].concat(recents.filter(function (item) { return item !== keyword; })).slice(0, 20);
saveJson(STORAGE_KEYS.RECENT, next);
renderRecentSearches();
}
function setStatus(message, type) {
if (!statusEl) {
return;
}
statusEl.textContent = message;
statusEl.classList.remove('text-red-600', 'text-blue-700', 'text-green-700', 'text-amber-700');
if (type === 'error') {
statusEl.classList.add('text-red-600');
} else if (type === 'loading') {
statusEl.classList.add('text-blue-700');
} else if (type === 'warn') {
statusEl.classList.add('text-amber-700');
} else {
statusEl.classList.add('text-green-700');
}
}
function updateCoords(coords) {
if (!coordsEl) {
return;
}
coordsEl.textContent = '(' + coords.lat.toFixed(4) + ', ' + coords.lon.toFixed(4) + ')';
}
function updateDirectionsState() {
if (!directionsBtn) {
return;
}
const enabled = Boolean((state.startPoint || state.currentPosition) && state.destination);
directionsBtn.disabled = !enabled;
directionsBtn.classList.toggle('opacity-50', !enabled);
directionsBtn.classList.toggle('cursor-not-allowed', !enabled);
}
async function geocodeSingle(query, cachePrefix) {
const url = 'https://nominatim.openstreetmap.org/search?format=json&limit=1&addressdetails=1&q=' + encodeURIComponent(query);
const cacheKey = cachePrefix + query;
try {
const data = await fetchJsonWithTimeout(url, {
headers: {
'Accept-Language': 'ko'
}
}, SEARCH_TIMEOUT_MS);
saveJson(cacheKey, data);
if (!Array.isArray(data) || data.length === 0) {
return null;
}
return data[0];
} catch {
const cached = loadJson(cacheKey, []);
if (Array.isArray(cached) && cached.length > 0) {
return cached[0];
}
return null;
}
}
function setRouteSummary(message) {
if (!routeSummaryEl) {
return;
}
routeSummaryEl.textContent = message;
}
function setFareSummary(message) {
if (!routeFareSummaryEl) {
return;
}
routeFareSummaryEl.textContent = message;
}
function setComboSummary(message) {
if (!comboSummaryEl) {
return;
}
comboSummaryEl.textContent = message;
}
function setMenuOpen(open) {
document.body.classList.toggle('menu-open', Boolean(open));
}
function formatCurrency(krw) {
return Math.round(krw).toLocaleString('ko-KR') + '원';
}
function formatDistance(distanceM) {
if (distanceM < 1000) {
return Math.round(distanceM) + 'm';
}
return (distanceM / 1000).toFixed(1) + 'km';
}
function formatDuration(durationSec) {
const totalMin = Math.round(durationSec / 60);
if (totalMin < 60) {
return totalMin + '분';
}
const hour = Math.floor(totalMin / 60);
const min = totalMin % 60;
return hour + '시간 ' + min + '분';
}
function speedKmH(mode) {
if (mode === 'walking') return 4.5;
if (mode === 'cycling') return 15;
if (mode === 'subway') return 32;
if (mode === 'bus') return 24;
if (mode === 'taxi') return 28;
if (mode === 'flight') return 780;
return 40;
}
function clearRoute() {
if (state.routeLayer) {
state.routeLayer.remove();
state.routeLayer = null;
}
}
function estimateFare(mode, distanceKm, durationMin) {
const km = Math.max(0, Number(distanceKm) || 0);
const min = Math.max(0, Number(durationMin) || 0);
const nowHour = new Date().getHours();
const isLateNight = nowHour >= 22 || nowHour < 4;
if (mode === 'walking') {
return {
total: 0,
breakdown: '도보는 요금이 없습니다.',
};
}
if (mode === 'cycling') {
const base = 1000;
const extra = Math.max(0, Math.ceil(Math.max(0, min - 60) / 5) * 200);
return {
total: base + extra,
breakdown: '공공자전거 기준(기본 60분 ' + formatCurrency(base) + ' + 추가 5분당 200원)',
};
}
if (mode === 'subway') {
const base = 1550;
const firstSection = Math.max(0, Math.min(km, 50) - 10);
const secondSection = Math.max(0, km - 50);
const extra = Math.ceil(firstSection / 5) * 100 + Math.ceil(secondSection / 8) * 100;
return {
total: base + extra,
breakdown: '수도권 지하철 성인 교통카드 기준(10km 초과 5km당 100원, 50km 초과 8km당 100원)',
};
}
if (mode === 'bus') {
const base = 1500;
const firstSection = Math.max(0, Math.min(km, 40) - 10);
const secondSection = Math.max(0, km - 40);
const extra = Math.ceil(firstSection / 5) * 100 + Math.ceil(secondSection / 8) * 100;
return {
total: base + extra,
breakdown: '시내/광역 버스 단순화 기준(10km 초과 5km당 100원, 40km 초과 8km당 100원)',
};
}
if (mode === 'taxi') {
const base = 4800;
const overM = Math.max(0, km * 1000 - 1600);
const distanceUnits = Math.ceil(overM / 131);
const expectedDriveMin = km * 2.5;
const delayMin = Math.max(0, min - expectedDriveMin);
const timeUnits = Math.ceil((delayMin * 60) / 30);
const meter = (distanceUnits + Math.max(0, timeUnits)) * 100;
const nightSurcharge = isLateNight ? (base + meter) * 0.2 : 0;
const total = base + meter + nightSurcharge;
return {
total: total,
breakdown: '서울 중형택시 단순 추정(기본 1.6km 4,800원 + 거리/시간 병산, 심야 20% 가산 ' + (isLateNight ? '적용' : '미적용') + ')',
};
}
if (mode === 'flight') {
const base = 35000;
const distancePart = km * 90;
const tax = 13000;
const service = 3000;
return {
total: base + distancePart + tax + service,
breakdown: '국내선 단순 추정(운임 + 공항세/유류할증 + 발권수수료)',
};
}
const fuelPricePerL = 1700;
const fuelEfficiencyKmPerL = 12;
const fuelCost = (km / fuelEfficiencyKmPerL) * fuelPricePerL;
const tollCost = km * 70;
const parkingCost = min >= 30 ? 2000 : 0;
return {
total: fuelCost + tollCost + parkingCost,
breakdown: '자가용 추정(연료비 + 통행료 + 주차비 일부)',
};
}
function modeLabel(mode) {
if (mode === 'walking') return '도보';
if (mode === 'cycling') return '자전거';
if (mode === 'subway') return '지하철';
if (mode === 'bus') return '버스';
if (mode === 'taxi') return '택시';
if (mode === 'flight') return '비행기';
return '차량';
}
function updateRouteModeUI() {
routeModeButtons.forEach(function (btn) {
const mode = btn.getAttribute('data-route-mode');
const active = mode === state.routeMode;
btn.classList.toggle('bg-primary-container/30', active);
btn.classList.toggle('text-on-surface', active);
btn.classList.toggle('border', !active);
btn.classList.toggle('border-outline-variant', !active);
});
}
function setRouteMode(mode) {
state.routeMode = mode || 'driving';
updateRouteModeUI();
clearRoute();
setRouteSummary(modeLabel(state.routeMode) + ' 모드 선택됨. 내부 길찾기를 눌러 경로를 계산하세요.');
setFareSummary('예상 요금: -');
}
function updateRadiusLabel() {
if (!nearbyRadiusLabel) {
return;
}
nearbyRadiusLabel.textContent = (state.nearbyRadiusM / 1000).toFixed(1) + 'km';
}
function ensureMap() {
if (!mapEl || typeof L === 'undefined') {
return null;
}
if (state.map) {
return state.map;
}
state.map = L.map('map', { zoomControl: false }).setView([DEFAULT_CENTER.lat, DEFAULT_CENTER.lon], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(state.map);
// Allow quick destination pinning without typing.
state.map.on('click', function (event) {
const lat = Number(event.latlng.lat);
const lon = Number(event.latlng.lng);
const label = '지정한 위치 (' + lat.toFixed(4) + ', ' + lon.toFixed(4) + ')';
state.destination = { lat: lat, lon: lon, label: label };
clearRoute();
setRouteSummary('목적지가 변경되었습니다. 내부 길찾기를 눌러 경로를 계산하세요.');
setFareSummary('예상 요금: -');
setDestinationMarker(lat, lon, label);
updateDirectionsState();
saveJson(STORAGE_KEYS.DESTINATION, state.destination);
setStatus('지도를 눌러 목적지를 지정했습니다.', 'success');
});
state.map.on('moveend', function () {
const center = state.map.getCenter();
saveJson(STORAGE_KEYS.VIEW, {
lat: center.lat,
lon: center.lng,
zoom: state.map.getZoom(),
});
});
state.nearbyLayer = L.layerGroup().addTo(state.map);
return state.map;
}
function setUserMarker(lat, lon) {
const map = ensureMap();
if (!map) {
return;
}
const userArrowIcon = L.divIcon({
className: 'lmn-user-arrow-icon',
html: '<div style="width:0;height:0;border-left:9px solid transparent;border-right:9px solid transparent;border-bottom:18px solid #d32f2f;filter:drop-shadow(0 1px 2px rgba(0,0,0,.35));transform:rotate(0deg);"></div>',
iconSize: [18, 18],
iconAnchor: [9, 16],
popupAnchor: [0, -12],
});
if (state.userMarker) {
state.userMarker.setLatLng([lat, lon]);
} else {
state.userMarker = L.marker([lat, lon], {
icon: userArrowIcon,
zIndexOffset: 1200,
}).addTo(map).bindPopup('내 위치');
}
}
function setStartMarker(lat, lon, label) {
const map = ensureMap();
if (!map) {
return;
}
if (state.startMarker) {
state.startMarker.setLatLng([lat, lon]);
state.startMarker.setPopupContent(label || '출발지');
} else {
state.startMarker = L.circleMarker([lat, lon], {
radius: 8,
color: '#006e1c',
fillColor: '#006e1c',
fillOpacity: 0.9,
weight: 2,
}).addTo(map).bindPopup(label || '출발지');
}
}
function setDestinationMarker(lat, lon, label) {
const map = ensureMap();
if (!map) {
return;
}
if (state.destinationMarker) {
state.destinationMarker.setLatLng([lat, lon]);
state.destinationMarker.setPopupContent(label || '목적지');
} else {
state.destinationMarker = L.marker([lat, lon]).addTo(map).bindPopup(label || '목적지');
}
}
function haversineKm(a, b) {
const toRad = function (deg) { return deg * Math.PI / 180; };
const dLat = toRad(b.lat - a.lat);
const dLon = toRad(b.lon - a.lon);
const s1 = Math.sin(dLat / 2);
const s2 = Math.sin(dLon / 2);
const x = s1 * s1 + Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * s2 * s2;
return 6371 * 2 * Math.atan2(Math.sqrt(x), Math.sqrt(1 - x));
}
function buildGreatCirclePath(start, end, segments) {
const count = Math.max(12, Number(segments) || 64);
const toRad = function (deg) { return deg * Math.PI / 180; };
const toDeg = function (rad) { return rad * 180 / Math.PI; };
const lat1 = toRad(start.lat);
const lon1 = toRad(start.lon);
const lat2 = toRad(end.lat);
const lon2 = toRad(end.lon);
const sinLat1 = Math.sin(lat1);
const cosLat1 = Math.cos(lat1);
const sinLat2 = Math.sin(lat2);
const cosLat2 = Math.cos(lat2);
const delta = 2 * Math.asin(Math.sqrt(
Math.pow(Math.sin((lat2 - lat1) / 2), 2) +
cosLat1 * cosLat2 * Math.pow(Math.sin((lon2 - lon1) / 2), 2)
));
if (!Number.isFinite(delta) || delta === 0) {
return [
[start.lat, start.lon],
[end.lat, end.lon],
];
}
const points = [];
for (let i = 0; i <= count; i += 1) {
const f = i / count;
const A = Math.sin((1 - f) * delta) / Math.sin(delta);
const B = Math.sin(f * delta) / Math.sin(delta);
const x = A * cosLat1 * Math.cos(lon1) + B * cosLat2 * Math.cos(lon2);
const y = A * cosLat1 * Math.sin(lon1) + B * cosLat2 * Math.sin(lon2);
const z = A * sinLat1 + B * sinLat2;
const lat = Math.atan2(z, Math.sqrt(x * x + y * y));
const lon = Math.atan2(y, x);
points.push([toDeg(lat), toDeg(lon)]);
}
return points;
}
function interpolatePoint(a, b, ratio) {
const r = clamp(Number(ratio) || 0.5, 0, 1);
return {
lat: a.lat + (b.lat - a.lat) * r,
lon: a.lon + (b.lon - a.lon) * r,
};
}
function legColor(mode) {
if (mode === 'walking') return '#2e7d32';
if (mode === 'subway') return '#6a1b9a';
if (mode === 'bus') return '#ef6c00';
if (mode === 'taxi') return '#f9a825';
if (mode === 'flight') return '#1565c0';
if (mode === 'cycling') return '#00838f';
return '#546e7a';
}
function comboPreset(preset, origin, destination) {
const t1 = interpolatePoint(origin, destination, 0.25);
const t2 = interpolatePoint(origin, destination, 0.75);
if (preset === 'walk-subway-walk') {
return [
{ mode: 'walking', from: origin, to: t1 },
{ mode: 'subway', from: t1, to: t2 },
{ mode: 'walking', from: t2, to: destination },
];
}
if (preset === 'walk-bus-walk') {
return [
{ mode: 'walking', from: origin, to: t1 },
{ mode: 'bus', from: t1, to: t2 },
{ mode: 'walking', from: t2, to: destination },
];
}
if (preset === 'taxi-subway-walk') {
return [
{ mode: 'taxi', from: origin, to: t1 },
{ mode: 'subway', from: t1, to: t2 },
{ mode: 'walking', from: t2, to: destination },
];
}
if (preset === 'drive-flight-drive') {
const a1 = interpolatePoint(origin, destination, 0.1);
const a2 = interpolatePoint(origin, destination, 0.9);
return [
{ mode: 'driving', from: origin, to: a1 },
{ mode: 'flight', from: a1, to: a2 },
{ mode: 'driving', from: a2, to: destination },
];
}
if (preset === 'bike-subway-walk') {
return [
{ mode: 'cycling', from: origin, to: t1 },
{ mode: 'subway', from: t1, to: t2 },
{ mode: 'walking', from: t2, to: destination },
];
}
return [];
}
function linePathForLeg(leg) {
if (leg.mode === 'flight') {
return buildGreatCirclePath(leg.from, leg.to, 48);
}
return [
[leg.from.lat, leg.from.lon],
[leg.to.lat, leg.to.lon],
];
}
async function planCombinedRoute() {
const preset = routeComboSelectEl ? routeComboSelectEl.value : '';
const origin = state.startPoint || state.currentPosition;
if (!preset) {
setStatus('조합 경로 프리셋을 선택해 주세요.', 'warn');
return;
}
if (!origin || !state.destination) {
setStatus('출발지와 목적지를 먼저 설정해 주세요.', 'warn');
return;
}
const legs = comboPreset(preset, origin, state.destination);
if (legs.length === 0) {
setStatus('지원하지 않는 조합 경로입니다.', 'error');
return;
}
const map = ensureMap();
if (!map) {
return;
}
clearRoute();
const group = L.layerGroup().addTo(map);
state.routeLayer = group;
let totalKm = 0;
let totalMin = 0;
let totalFare = 0;
const parts = [];
const boundsPoints = [];
legs.forEach(function (leg) {
const km = haversineKm(leg.from, leg.to) * (leg.mode === 'flight' ? 1.07 : 1);
const min = (km / speedKmH(leg.mode)) * 60 + (leg.mode === 'subway' ? 6 : 0) + (leg.mode === 'bus' ? 4 : 0);
const fare = estimateFare(leg.mode, km, min);
totalKm += km;
totalMin += min;
totalFare += fare.total;
parts.push(modeLabel(leg.mode) + ' ' + km.toFixed(1) + 'km');
const path = linePathForLeg(leg);
path.forEach(function (p) { boundsPoints.push(p); });
L.polyline(path, {
color: legColor(leg.mode),
weight: leg.mode === 'flight' ? 5 : 4,
opacity: 0.9,
dashArray: leg.mode === 'walking' ? '5 6' : undefined,
}).addTo(group);
});
if (boundsPoints.length > 1) {
map.fitBounds(L.latLngBounds(boundsPoints), { padding: [24, 24] });
}
setRouteSummary('조합 경로: ' + parts.join(' → ') + ' / 총 ' + totalKm.toFixed(1) + 'km / 예상 ' + formatDuration(totalMin * 60));
setFareSummary('예상 요금: ' + formatCurrency(totalFare));
setComboSummary('구간별 계산 완료: ' + parts.join(' | '));
setStatus('조합 경로를 계산해 지도에 표시했습니다.', 'success');
}
async function fetchJsonWithTimeout(url, options, timeoutMs) {
const controller = new AbortController();
const timer = setTimeout(function () { controller.abort(); }, timeoutMs);
try {
const response = await fetch(url, {
method: options.method || 'GET',
headers: options.headers || {},
body: options.body,
signal: controller.signal,
});
if (!response.ok) {
throw new Error('HTTP ' + response.status);
}
return await response.json();
} finally {
clearTimeout(timer);
}
}
async function getCurrentPositionOnce() {
if (state.currentPosition && Number.isFinite(state.currentPosition.lat) && Number.isFinite(state.currentPosition.lon)) {
return state.currentPosition;
}
return await new Promise(function (resolve, reject) {
if (!navigator.geolocation) {
reject(new Error('Geolocation unsupported'));
return;
}
navigator.geolocation.getCurrentPosition(
function (position) {
const point = {
lat: position.coords.latitude,
lon: position.coords.longitude,
};
resolve(point);
},
function (err) {
reject(err || new Error('Position unavailable'));
},
{ enableHighAccuracy: true, timeout: 8000, maximumAge: 0 }
);
});
}
async function resolveMyLocationAddress() {
const point = await getCurrentPositionOnce();
const lat = Number(point.lat);
const lon = Number(point.lon);
state.currentPosition = { lat: lat, lon: lon };
state.startPoint = { lat: lat, lon: lon, label: '내 위치' };
saveJson(STORAGE_KEYS.POSITION, state.currentPosition);
saveJson(STORAGE_KEYS.START, state.startPoint);
updateCoords(state.currentPosition);
setUserMarker(lat, lon);
setStartMarker(lat, lon, '내 위치');
const reverseUrl = 'https://nominatim.openstreetmap.org/reverse?format=json&lat=' + encodeURIComponent(String(lat)) + '&lon=' + encodeURIComponent(String(lon));
const data = await fetchJsonWithTimeout(reverseUrl, {
headers: {
'Accept-Language': 'ko'
}
}, SEARCH_TIMEOUT_MS);
const label = (data && (data.display_name || data.name)) ? (data.display_name || data.name) : '내 위치';
return {
lat: lat,
lon: lon,
label: label,
};
}
async function locateUser() {
if (!navigator.geolocation) {
setStatus('이 브라우저는 위치 기능을 지원하지 않습니다.', 'error');
return;
}
setStatus('내 위치를 확인 중입니다...', 'loading');
navigator.geolocation.getCurrentPosition(
function (position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
state.currentPosition = { lat: lat, lon: lon };
state.startPoint = { lat: lat, lon: lon, label: '내 위치' };
saveJson(STORAGE_KEYS.START, state.startPoint);
saveJson(STORAGE_KEYS.POSITION, state.currentPosition);
updateCoords(state.currentPosition);
setUserMarker(lat, lon);
setStartMarker(lat, lon, '내 위치');
const map = ensureMap();
if (map) {
map.setView([lat, lon], 15);
}
updateDirectionsState();
setStatus('내 위치를 찾았습니다.', 'success');
},
function (err) {
if (err && err.code === err.PERMISSION_DENIED) {
setStatus('위치 권한이 필요합니다. 브라우저 설정을 확인해 주세요.', 'warn');
} else {
setStatus('위치 확인에 실패했습니다. 다시 시도해 주세요.', 'error');
}
},
{ enableHighAccuracy: true, timeout: 8000, maximumAge: 0 }
);
}
async function searchDestination() {
const query = (inputEl ? inputEl.value : '').trim();
if (!query) {
setStatus('목적지를 입력해 주세요.', 'warn');
return;
}
if (query.length > 80) {
setStatus('검색어는 80자 이하로 입력해 주세요.', 'warn');
return;
}
if (query === '내 위치') {
setStatus('내 위치 주소를 확인 중입니다...', 'loading');
try {
const mine = await resolveMyLocationAddress();
if (inputEl) {
inputEl.value = mine.label;
}
state.destination = { lat: mine.lat, lon: mine.lon, label: mine.label };
clearRoute();
setRouteSummary('목적지가 변경되었습니다. 내부 길찾기를 눌러 경로를 계산하세요.');
setFareSummary('예상 요금: -');
setDestinationMarker(mine.lat, mine.lon, mine.label);
pushRecentSearch('내 위치');
const map = ensureMap();
if (map) {
map.setView([mine.lat, mine.lon], 15);
}
updateDirectionsState();
setStatus('내 위치 주소를 목적지에 입력했습니다.', 'success');
return;
} catch (_error) {
setStatus('내 위치 주소 확인에 실패했습니다. 위치 권한과 네트워크를 확인해 주세요.', 'error');
return;
}
}
setStatus('목적지를 검색 중입니다...', 'loading');
try {
const top = await geocodeSingle(query, 'lmn-geocode:');
if (!top) {
setStatus('검색 결과가 없습니다. 다른 키워드를 입력해 주세요.', 'warn');
return;
}
const lat = Number(top.lat);
const lon = Number(top.lon);
const label = top.display_name || query;
state.destination = { lat: lat, lon: lon, label: label };
clearRoute();
setRouteSummary('목적지가 변경되었습니다. 내부 길찾기를 눌러 경로를 계산하세요.');
setFareSummary('예상 요금: -');
setDestinationMarker(lat, lon, label);
pushRecentSearch(query);
const map = ensureMap();
if (map) {
map.setView([lat, lon], 15);
}
updateDirectionsState();
setStatus('목적지를 찾았습니다.', 'success');
} catch (error) {
setStatus('목적지 검색에 실패했습니다. 잠시 후 다시 시도해 주세요.', 'error');
}
}
async function searchStart() {
const query = (startInputEl ? startInputEl.value : '').trim();
if (!query) {
setStatus('출발지를 입력해 주세요.', 'warn');
return;
}
if (query.length > 80) {
setStatus('검색어는 80자 이하로 입력해 주세요.', 'warn');
return;
}
if (query === '내 위치') {
setStatus('내 위치 주소를 확인 중입니다...', 'loading');
try {
const mine = await resolveMyLocationAddress();
state.startPoint = { lat: mine.lat, lon: mine.lon, label: mine.label };
saveJson(STORAGE_KEYS.START, state.startPoint);
clearRoute();
setRouteSummary('출발지가 변경되었습니다. 내부 길찾기를 눌러 경로를 계산하세요.');
setFareSummary('예상 요금: -');
setStartMarker(mine.lat, mine.lon, mine.label);
if (startInputEl) {
startInputEl.value = mine.label;
}
const map = ensureMap();
if (map) {
map.setView([mine.lat, mine.lon], 15);
}
updateDirectionsState();
setStatus('내 위치 주소를 출발지에 입력했습니다.', 'success');
return;
} catch (_error) {
setStatus('내 위치 주소 확인에 실패했습니다. 위치 권한과 네트워크를 확인해 주세요.', 'error');
return;
}
}
setStatus('출발지를 검색 중입니다...', 'loading');
try {
const top = await geocodeSingle(query, 'lmn-geocode-start:');
if (!top) {
setStatus('검색 결과가 없습니다. 다른 키워드를 입력해 주세요.', 'warn');
return;