-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathapp.js
More file actions
241 lines (195 loc) · 8.77 KB
/
app.js
File metadata and controls
241 lines (195 loc) · 8.77 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
// const baseUrl = "http://localhost:3000";
const baseUrl = 'https://miniature-purple-scissor.glitch.me';
// 📌 장소 목록 조회
async function fetchBaseList(tourValue) {
try {
const response = await fetch(`${baseUrl}/baselist?tourValue=${tourValue}&lat=${window.selectedLatlng.lat}&lng=${window.selectedLatlng.lng}`);
// const data = await response.text(); // JSON 대신 text로 받아보기
// console.log("📌 응답 본문:", data);
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
const data = await response.json();
// contentid만 추출하여 배열로 반환
console.log(data);
return data;
} catch (error) {
console.error('Error fetching content IDs:', error);
return [];
}
}
// 📌 개별 API 호출 (각 contentid에 대해 호출)
async function fetchDetail(contentId) {
try {
const response = await fetch(`${baseUrl}/tour/detail?contentId=${contentId}`);
// const data = await response.text(); // JSON 대신 text로 받아보기
// console.log("📌 응답 본문:", data);
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
const data = await response.json();
return data; // 상세 정보 반환
} catch (error) {
console.error(`Error fetching details for contentId ${contentId}:`, error);
return null;
}
}
function getSelectedTourValue() {
const selectedRadio = document.querySelector('input[name="tourType"]:checked');
if (selectedRadio) {
return selectedRadio.value;
}
return ''; // 아무것도 선택되지 않았을 경우
}
// 📌 모든 API 호출 실행
async function fetchAllDetails() {
// 관광 카테고리
const tourValue = getSelectedTourValue();
console.log(tourValue + '\n');
// 장소 기본 정보
if (!window.selectedLatlng?.lng || !window.selectedLatlng?.lat) {
// 객체가 없을 경우 먼저 생성
if (!window.selectedLatlng) {
window.selectedLatlng = {};
}
// 기본 위치 설정 (서울시청 좌표)
window.selectedLatlng.lng = 126.97865225753738;
window.selectedLatlng.lat = 37.566842224638414;
}
const data = await fetchBaseList(tourValue);
// 만약에 data가 없다면 종료
if (data.length === 0) {
// 로딩 스피너 비활성화
document.getElementById('spinner').innerHTML = '';
console.log('주위의 정보 없음', data);
const resultDiv = document.getElementById('result');
const div = document.createElement('div');
// 조회된 관광/숙소가 없음
const message = document.createElement('p');
message.textContent = '조회된 관광/숙소가 없음';
div.appendChild(message);
// resultDiv 안에 추가
resultDiv.appendChild(div);
return;
}
// contentid 배열 가져오기
const contentIds = data.map(item => item.contentid);
console.log('📌 가져온 contentId 목록:', contentIds);
if (contentIds.length === 0) {
console.error('📌 contentId가 없습니다.');
return;
}
// Promise.all()로 모든 API 호출 실행
const detailsArray = await Promise.all(contentIds.map(fetchDetail));
console.log(detailsArray);
// 📌 배열 내부 구조 확인 후 문자열 변환
const detailsString = detailsArray
.map((detail, index) => {
if (!detail || !Array.isArray(detail) || detail.length === 0) return null;
const item = detail[0]; // 첫 번째 요소 가져오기
// 장소의 속성 정리
Object.keys(item).forEach(key => {
if (typeof item[key] === 'string') {
item[key] = item[key].replace(/[-\s]+/g, ' ').trim();
}
});
const info = data[index];
const title = info.title;
const addr = `${info.addr1} ${info.addr2}`;
return `${index}번 장소 이름: ${title} 상세 주소: ${addr} 사고 예방 및 응급 조치 관련 정보: ${item.relaAcdntRiskMtr}, 반려동물 동반 가능 구역 정보: ${item.acmpyTypeCd}, 관련 시설: ${item.relaPosesFclty}, 제공되는 반려동물 관련 용품: ${item.relaFrnshPrdlst}, 기타 동반 정보: ${item.etcAcmpyInfo}, 구매 가능한 제품 목록: ${item.relaPurcPrdlst}, 동반 가능한 반려견 기준: ${item.acmpyPsblCpam}, 대여 관련 제품 목록: ${item.relaRntlPrdlst}, 필수 동반 조건: ${item.acmpyNeedMtr}`;
})
.filter(item => item !== null) // null 값 제거
.join('\n'); // 줄바꿈으로 연결
// pet 정보
// 각 input 필드의 값을 가져오기
const name = document.getElementById('petName').value.trim();
const species = document.getElementById('petSpecies').value.trim();
const size = document.getElementById('petSizeBtn').textContent !== '선택' ? document.getElementById('petSizeBtn').textContent.trim() : '선택 안 함';
const isPredator = document.getElementById('isPredatorBtn').textContent !== '선택' ? document.getElementById('isPredatorBtn').textContent.trim() : '선택 안 함';
const isPublicFriendly = document.getElementById('publicAccessBtn').textContent !== '선택' ? document.getElementById('publicAccessBtn').textContent.trim() : '선택 안 함';
// 값을 하나의 문자열로 연결
const petInfo = `이름: ${name}, 종: ${species}, 크기: ${size}, 맹수 여부: ${isPredator}, 공공장소 동행 가능 여부: ${isPublicFriendly}`;
const prompt = '숙소 정보:\n' + detailsString + '\n반려동물 정보:\n' + petInfo;
console.log('📌 숙소 정보, 펫 정보:\n', prompt);
// gemini에게 물어봅시다..
const url = `https://miniature-purple-scissor.glitch.me/gemini?type=${tourValue}`;
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify({
text: prompt,
}),
// Content-Type 꼭!
headers: {
'Content-Type': 'Application/json',
},
});
const json = await response.json();
let infoList = JSON.parse(json.reply);
// 화면에 보여주는 함수
displayInfo(infoList, data, tourValue);
}
function displayInfo(infoList, data, tourValue) {
const resultDiv = document.getElementById('result');
// 조건에 부합되는 관광/숙소가 없다면
if (infoList[0] === -1 || infoList.length === 0) {
const div = document.createElement('div');
// 반려 동물 정보에 맞는 관광/숙소가 없음
const message = document.createElement('p');
message.textContent = '반려 동물 정보에 맞는 관광/숙소가 없음';
div.appendChild(message);
// resultDiv 안에 추가
resultDiv.appendChild(div);
} else {
// data 배열에서 각 숙소의 정보 출력
for (const [index, placeInfo] of infoList.entries()) {
const item = data[placeInfo.NUMBER]; // 번호에 맞는 숙소 정보
const div = document.createElement('div');
div.classList.add('info-card');
div.id = `${tourValue}-${index}`; // 인덱스를 기반으로 id 설정
// 숙소 이름
const title = document.createElement('h3');
title.classList.add('info-name');
title.textContent = item.title;
div.appendChild(title);
// 숙소 주소
const address = document.createElement('p');
address.classList.add('info-address');
address.textContent = `📍 ${item.addr1} ${item.addr2}`;
div.appendChild(address);
// 숙소 이미지 (없으면 대체 이미지 설정)
const image = document.createElement('img');
image.classList.add('info-image');
if (item.firstimage) {
image.src = item.firstimage;
} else {
image.src = './asset/notfound.png'; // 기본 이미지 경로
}
image.alt = item.title;
image.style.width = '50%'; // 이미지 크기 조절
div.appendChild(image);
// 주요특징
const info = document.createElement('p');
info.classList.add('info-description');
info.textContent = `🔍 ${placeInfo.INFO && placeInfo.INFO.trim() ? placeInfo.INFO : '정보 없음'}`;
div.appendChild(info);
// 운영시간
const time = document.createElement('p');
time.classList.add('info-hours');
time.textContent = `📅 ${placeInfo.TIME && placeInfo.TIME.trim() ? placeInfo.TIME : '정보 없음'}`;
div.appendChild(time);
// 전화번호
const tel = document.createElement('p');
time.classList.add('info-phone');
tel.textContent = `📞 ${item.tel && item.tel.trim() ? item.tel : '정보 없음'}`;
div.appendChild(tel);
/*
// 숙소 링크 (필요시 추가)
const link = document.createElement("a");
link.href = `http://tour.visitkorea.or.kr/${item.contentid}`;
link.target = "_blank";
link.textContent = "상세보기";
div.appendChild(link);
*/
resultDiv.appendChild(div);
}
}
// 로딩 스피너 비활성화
document.getElementById('spinner').innerHTML = '';
}
document.getElementById('fetchButton').addEventListener('click', fetchAllDetails);