-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.html
More file actions
497 lines (447 loc) · 19.7 KB
/
Copy pathindex.html
File metadata and controls
497 lines (447 loc) · 19.7 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>GeoAI 대시보드</title>
<script src='https://unpkg.com/maplibre-gl@4.1.3/dist/maplibre-gl.js'></script>
<link href='https://unpkg.com/maplibre-gl@4.1.3/dist/maplibre-gl.css' rel='stylesheet' />
<style>
/* (기존 CSS와 동일) */
body { margin: 0; padding: 0; font-family: sans-serif; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
#controls {
position: absolute; top: 20px; left: 20px; background: white;
padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);
z-index: 10; width: 300px; max-height: 90vh; overflow-y: auto;
transition: transform 0.3s ease;
}
#infoContainer {
position: absolute;
top: 20px;
right: 20px;
width: 340px; /* 300px (패널) + 40px (패딩) */
z-index: 10;
transition: transform 0.3s ease;
transform: translateX(0); /* 기본 상태: 보임 */
}
#infoContainer.closed {
transform: translateX(340px);
}
#infoPanel {
width: 300px;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
max-height: 90vh;
overflow-y: auto;
float: right; /* 컨테이너의 오른쪽에 붙임 */
}
#infoToggleBtn {
position: absolute;
top: 0;
left: 0; /* 컨테이너의 왼쪽에 붙임 */
width: 40px;
height: 40px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
border-radius: 8px 0 0 8px; /* 왼쪽만 둥글게 */
font-size: 16px;
font-weight: bold;
box-shadow: -2px 2px 10px rgba(0,0,0,0.1);
}
#status {
margin-top: 15px; font-size: 14px; color: #555; min-height: 40px;
}
#textInput {
width: 100%; height: 60px; padding: 10px; font-size: 14px;
border: 1px solid #ccc; border-radius: 5px; box-sizing: border-box;
margin-bottom: 10px; resize: vertical; font-family: sans-serif;
}
#style-switcher { margin-bottom: 10px; }
#style-switcher h4 { margin: 0 0 5px 0; }
#mapStyleSelect {
width: 100%; padding: 8px; font-size: 14px; border: 1px solid #ccc;
border-radius: 5px; background-color: white;
}
#answerBox {
margin-top: 15px; padding: 10px; background: #f4f4f4;
border-radius: 5px; display: none;
}
#sqlResult {
position: absolute; bottom: 20px; left: 20px;
background: rgba(0,0,0,0.7); color: white; padding: 10px;
border-radius: 5px; z-index: 10; font-family: monospace;
max-width: 500px; max-height: 200px; overflow-y: auto;
}
.maplibregl-popup-content {
padding: 10px; background: rgba(255, 255, 255, 0.9);
box-shadow: 0 1px 5px rgba(0,0,0,0.2); border-radius: 5px; font-size: 13px;
}
.maplibregl-popup-content strong { color: #333; }
</style>
</head>
<body>
<div id='map'></div>
<div id="controls">
<div id="style-switcher">
<h4>배경지도 선택</h4>
<select id="mapStyleSelect">
<option value="streets-v2" selected>Streets (기본)</option>
<option value="streets-v2-dark">Streets (Dark)</option>
<option value="satellite">Satellite (위성)</option>
<option value="hybrid">Hybrid (위성 + 라벨)</option>
<option value="topo-v2">Topo (지형)</option>
<option value="basic-v2">Basic (단순)</option>
</select>
</div>
<hr style="margin: 20px 0;">
<h3>음성 명령</h3>
<button id="btnVoice" disabled>🎙️ (지도 로딩 중...)</button>
<div id="status">지도 로딩 중...</div>
<hr style="margin: 20px 0;">
<h3>텍스트 명령</h3>
<textarea id="textInput" placeholder="지도 로딩 중..." disabled></textarea>
<button id="btnSubmitText" disabled>분석 실행</button>
<div id="answerBox">
<h4>AI 답변:</h4>
<p id="answerText"></p>
</div>
</div>
<div id="infoContainer">
<div id="infoPanel">
<p style="font-size: 14px;">음성/텍스트로 지도 검색 및 공간분석을 할 수 있는 서비스</p>
<h4>1. 일반</h4>
<ul>
<li>네가 지도로 할 수 있는 예문을 보여줘</li>
<li>네가 가진 데이터 목록을 보여줘</li>
</ul>
<h4>2. 지도 검색</h4>
<ul>
<li>대림역 위치를 보여줘</li>
</ul>
<h4>3. 지도 제어</h4>
<ul>
<li>지도 축소해줘</li>
<li>지도를 왼쪽으로 이동해줘</li>
<li>위성 지도로 바꿔줘</li>
<li>지도를 3D 뷰로 보여줘</li>
</ul>
<h4>4. 공간 분석</h4>
<ul>
<li>대림역에서 가장 가까운 명인만두 위치를 보여줘</li>
<li>대림역에서 100미터 반경 영역을 그려서 보여줘</li>
<li>대림역 반경 250미터 내에 있는 분식집을 찾아줘</li>
<li>대림역에서 가장 가까운 건물 5개를 찾아줘</li>
<li>대림역에서 250미터 이내의 건물 중에서 50년 이상된 건물을 찾아서 각 건물의 위치와 함께 경계 영역을 그려줘</li>
</ul>
</div>
<button id="infoToggleBtn">></button>
</div>
<pre id="sqlResult"></pre>
<script>
// --- 1. UI 요소 ---
const btnVoice = document.getElementById('btnVoice');
const statusEl = document.getElementById('status');
const sqlResultEl = document.getElementById('sqlResult');
const textInput = document.getElementById('textInput');
const btnSubmitText = document.getElementById('btnSubmitText');
const answerBox = document.getElementById('answerBox');
const answerText = document.getElementById('answerText');
const styleSelect = document.getElementById('mapStyleSelect');
const speechRecognitionAvailable = window.SpeechRecognition || window.webkitSpeechRecognition;
const infoContainer = document.getElementById('infoContainer');
const infoToggleBtn = document.getElementById('infoToggleBtn');
const controlsPanel = document.getElementById('controls');
// --- 2. MapTiler 키 및 지도 초기화 ---
const mapTilerKey = 't2NOj07Xp2ihKwSzIP14';
const defaultStyle = 'streets-v2';
const baseCoords = [126.888018, 37.494571];
const map = new maplibregl.Map({
container: 'map',
style: `https://api.maptiler.com/maps/${defaultStyle}/style.json?key=${mapTilerKey}`,
center: baseCoords,
zoom: 15
});
// --- 3. 분석 레이어 추가 함수 (동일) ---
function setupAnalysisLayers() {
if (!map.getSource('analysis-results')) {
map.addSource('analysis-results', {
type: 'geojson',
data: { type: 'FeatureCollection', features: [] }
});
}
// 1. 폴리곤(영역) 레이어
if (!map.getLayer('results-polygons')) {
map.addLayer({
id: 'results-polygons', type: 'fill', source: 'analysis-results',
paint: { 'fill-color':'#0074D9', 'fill-opacity': 0.5 },
filter: ['==', ['geometry-type'], 'Polygon']
});
}
// 2. 점(포인트) 레이어 (단계구분도 포함)
if (!map.getLayer('results-points')) {
map.addLayer({
id: 'results-points', type: 'circle', source: 'analysis-results',
paint: {
'circle-color': [
'match', ['get', 'data_type'],
'building', '#FF4136',
'station', '#0074D9',
'subway_station', '#0074D9',
'1980년 이전', '#FFFF00',
'1980년대', '#FFC300',
'1990년대', '#FF5733',
'2000년대', '#C70039',
'2010년대', '#900C3F',
'2020년 이후', '#581845',
'#AAAAAA'
],
'circle-radius': 8, 'circle-stroke-width': 2, 'circle-stroke-color': '#FFFFFF'
},
filter: ['==', ['geometry-type'], 'Point']
});
}
// 3. 팝업 및 커서 이벤트 (동일)
map.on('click', (e) => {
const layersToQuery = ['results-points', 'results-polygons'];
if (!map.getLayer('results-points') || !map.getLayer('results-polygons')) {
return;
}
const features = map.queryRenderedFeatures(e.point, { layers: layersToQuery });
if (!features.length) {
return;
}
let pointFeature = features.find(f => f.layer.id === 'results-points');
let featureToShow = pointFeature ? pointFeature : features[0];
const properties = featureToShow.properties;
let htmlContent = "<div>";
for (const key in properties) {
if (key !== 'data_type') {
htmlContent += `<strong>${key}:</strong> ${properties[key]}<br>`;
}
}
htmlContent += "</div>";
new maplibregl.Popup().setLngLat(e.lngLat).setHTML(htmlContent).addTo(map);
});
map.on('mousemove', (e) => {
const layersToQuery = ['results-points', 'results-polygons'];
if (!map.getLayer('results-points') || !map.getLayer('results-polygons')) {
map.getCanvas().style.cursor = '';
return;
}
const features = map.queryRenderedFeatures(e.point, { layers: layersToQuery });
map.getCanvas().style.cursor = (features.length > 0) ? 'pointer' : '';
});
}
// --- 4. 지도 로딩 완료 이벤트 (동일) ---
map.on('load', () => {
setupAnalysisLayers();
statusEl.textContent = "지도 로딩 완료. 명령 대기 중...";
if (speechRecognitionAvailable) {
btnVoice.disabled = false;
btnVoice.textContent = "🎙️ (눌러서 말하기)";
}
textInput.disabled = false;
textInput.placeholder = "예: 녹번역 500미터 이내 건물\n(Enter로도 실행 가능)";
btnSubmitText.disabled = false;
});
// --- 5. 배경지도 변경 이벤트 (동일) ---
styleSelect.addEventListener('change', (e) => {
const styleId = e.target.value;
const newStyleUrl = `https://api.maptiler.com/maps/${styleId}/style.json?key=${mapTilerKey}`;
map.setStyle(newStyleUrl);
});
map.on('style.load', () => {
setupAnalysisLayers();
});
// --- 6. 오른쪽 패널 토글 이벤트 (동일) ---
infoToggleBtn.addEventListener('click', () => {
infoContainer.classList.toggle('closed');
if (infoContainer.classList.contains('closed')) {
infoToggleBtn.textContent = '<'; // 닫혔을 때
} else {
infoToggleBtn.textContent = '>'; // 열렸을 때 (default)
}
});
// --- 7. 텍스트 입력 (동일) ---
btnSubmitText.addEventListener('click', submitText);
textInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
submitText();
}
});
function submitText() {
const text = textInput.value.trim();
if (text === "") { return; }
statusEl.textContent = `입력된 텍스트: "${text}"`;
sqlResultEl.textContent = "";
answerBox.style.display = "none";
sendToBackend(text);
}
// --- 8. 백엔드 API 호출 (동일) ---
async function sendToBackend(text) {
statusEl.textContent = "백엔드에서 분석 중...";
const backendUrl = 'https://ai-sql-map-backend.onrender.com/analyze';
try {
const response = await fetch(backendUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: text })
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const result = await response.json();
if (result.type === "CLIENT_COMMAND") {
statusEl.textContent = "지도 제어 명령 수신.";
sqlResultEl.textContent = `[클라이언트 명령]\n${result.content}`;
handleClientCommand(result.content);
} else if (result.type === "FeatureCollection") {
statusEl.textContent = `분석 완료! ${result.features.length}개 결과 표시.`;
sqlResultEl.textContent = `[백엔드 정보]\nLLM이 생성한 SQL은 백엔드 터미널을 확인하세요.`;
updateMap(result);
answerBox.style.display = "none";
} else if (result.answer_text) {
statusEl.textContent = "AI 답변을 수신했습니다.";
answerText.textContent = result.answer_text;
answerBox.style.display = "block";
updateMap({ type: 'FeatureCollection', features: [] });
sqlResultEl.textContent = "[일반 텍스트 답변]";
} else if (result.error) {
statusEl.textContent = "분석 오류 발생!";
sqlResultEl.textContent = `[백엔드 에러]\n${result.error}\n\n[생성된 쿼리]\n${result.query || 'N/A'}`;
updateMap({ type: 'FeatureCollection', features: [] });
} else {
throw new Error("알 수 없는 백엔드 응답 형식입니다.");
}
} catch (error) {
console.error("Fetch Error:", error);
statusEl.textContent = "백엔드 서버 연결 실패!";
sqlResultEl.textContent = `백엔드 서버(${backendUrl}) 연결에 실패했습니다.\n(Error: ${error.message})\n\nRender.com 서버가 잠자기(cold start) 상태일 수 있습니다. 30초 후 다시 시도해 보세요.`;
}
}
// --- [수정] 9. 클라이언트 명령 처리 함수 (3D/Pitch 기능 추가) ---
function handleClientCommand(command) {
const panAmount = 100; // 100px
// 스타일 변경 헬퍼 함수
function changeMapStyle(styleValue) {
styleSelect.value = styleValue;
styleSelect.dispatchEvent(new Event('change'));
}
switch (command) {
// 지도 조작
case 'ZOOM_IN':
map.zoomIn({ duration: 300 });
break;
case 'ZOOM_OUT':
map.zoomOut({ duration: 300 });
break;
case 'PAN_TO_BASE':
map.easeTo({ center: baseCoords, zoom: 15, pitch: 0, bearing: 0 }); // [수정] 2D로 리셋
break;
// 지도 이동
case 'PAN_EAST':
map.panBy([panAmount, 0], { duration: 300 });
break;
case 'PAN_WEST':
map.panBy([-panAmount, 0], { duration: 300 });
break;
case 'PAN_NORTH':
map.panBy([0, -panAmount], { duration: 300 });
break;
case 'PAN_SOUTH':
map.panBy([0, panAmount], { duration: 300 });
break;
// [NEW] 시점 변경 (Pitch)
case 'SET_PITCH_3D':
map.easeTo({ pitch: 60, duration: 1000 }); // 60도 기울이기
break;
case 'SET_PITCH_2D':
map.easeTo({ pitch: 0, duration: 1000 }); // 0도 (평면)
break;
// [NEW] 끝
// 지도 스타일
case 'SET_STYLE_STREETS':
changeMapStyle('streets-v2');
break;
case 'SET_STYLE_DARK':
changeMapStyle('streets-v2-dark');
break;
case 'SET_STYLE_SATELLITE':
changeMapStyle('satellite');
break;
case 'SET_STYLE_HYBRID':
changeMapStyle('hybrid');
break;
case 'SET_STYLE_TOPO':
changeMapStyle('topo-v2');
break;
case 'SET_STYLE_BASIC':
changeMapStyle('basic-v2');
break;
default:
console.warn("Unknown client command:", command);
statusEl.textContent = "알 수 없는 지도 명령입니다.";
}
}
// --- 10. 지도 업데이트 함수 (동일) ---
function updateMap(geojson) {
try {
const source = map.getSource('analysis-results');
if (source) {
source.setData(geojson);
}
if (geojson.features.length > 0) {
const bounds = new maplibregl.LngLatBounds();
geojson.features.forEach(feature => {
if (feature.geometry.type === 'Point') {
bounds.extend(feature.geometry.coordinates);
} else if (feature.geometry.type === 'Polygon' && feature.geometry.coordinates) {
feature.geometry.coordinates.forEach(ring => {
ring.forEach(coord => {
bounds.extend(coord);
});
});
}
});
if (geojson.features.length === 1 && geojson.features[0].geometry.type === 'Point') {
map.flyTo({ center: geojson.features[0].geometry.coordinates, zoom: 16 });
} else {
map.fitBounds(bounds, { padding: 100 });
}
}
} catch (error) {
console.error("Map update error:", error);
statusEl.textContent = "지도 업데이트 중 오류 발생.";
}
}
// --- 11. 음성 인식 (동일) ---
if (speechRecognitionAvailable) {
const recognition = new SpeechRecognition();
recognition.lang = 'ko-KR';
recognition.continuous = false;
recognition.interimResults = false;
btnVoice.addEventListener('click', () => {
statusEl.textContent = "듣고 있습니다... 🎤";
btnVoice.style.backgroundColor = '#dc3545';
sqlResultEl.textContent = "";
answerBox.style.display = "none";
recognition.start();
});
recognition.onresult = (event) => {
const text = event.results[0][0].transcript;
statusEl.textContent = `인식된 Tекст: "${text}"`;
sendToBackend(text);
};
recognition.onend = () => {
btnVoice.style.backgroundColor = '#007bff';
};
recognition.onerror = (event) => {
statusEl.textContent = `음성 인식 오류: ${event.error}`;
};
}
</script>
</body>
</html>