-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhome_most_rated.html
199 lines (169 loc) · 8.42 KB
/
home_most_rated.html
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
<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Infinite Card Slider JavaScript | CodingNepal</title>
<link rel="stylesheet" href="css/home_most_rated.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Fontawesome Link for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
</head>
<body>
<div>
<h1>MOST RATED</h1>
</div>
<div class="wrapper">
<i id="left" class="fa-solid fa-angle-left"></i>
<ul class="carousel">
<!-- Cards will be generated dynamically here -->
</ul>
<i id="right" class="fa-solid fa-angle-right"></i>
</div>
<script>
let carousel;
// const API_PROTOCOL = 'http'
// const API_HOSTNAME = '13.229.101.17/api'
const API_PROTOCOL = 'https'
const API_HOSTNAME = 'goexplorebatangas.com/api'
const access_token = localStorage.getItem('access_token');
async function fetchPlacesData() {
try {
const response = await fetch(`${API_PROTOCOL}://${API_HOSTNAME}/places`);
const data = await response.json();
return Array.isArray(data) ? data : [];
} catch (error) {
console.error('Error fetching places data:', error);
return [];
}
}
async function fetchRatingsData() {
try {
const response = await fetch(`${API_PROTOCOL}://${API_HOSTNAME}/analytics/places/most-rated?limit=5`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${access_token}` // Use the correct variable name
}
});
const data = await response.json();
return Array.isArray(data) ? data : [];
} catch (error) {
console.error('Error fetching ratings data:', error);
return [];
}
}
function calculateAverageRating(ratings) {
if (ratings.length === 0) return 0;
const sum = ratings.reduce((total, rating) => total + parseFloat(rating), 0);
const average = (sum / ratings.length).toFixed(1);
return average;
}
async function populateCarousel() {
carousel = document.querySelector(".carousel");
// Fetch places and ratings data
const placesData = await fetchPlacesData();
const ratingsData = await fetchRatingsData();
// Create a map to store ratings for each place
const placeRatingsMap = new Map();
// Populate the placeRatingsMap with ratings data
ratingsData.forEach(rating => {
const placeId = rating.place_id;
const ratingValue = parseFloat(rating.avg_rating);
if (!placeRatingsMap.has(placeId)) {
placeRatingsMap.set(placeId, [ratingValue]);
} else {
placeRatingsMap.get(placeId).push(ratingValue);
}
});
// Calculate average ratings for each place
const placesWithRatings = placesData.map(place => {
const ratings = placeRatingsMap.get(place.id) || [];
const averageRating = calculateAverageRating(ratings);
return { ...place, averageRating };
});
// Sort places by average rating in descending order
placesWithRatings.sort((a, b) => b.averageRating - a.averageRating);
// Slice the top 5 places
const top5Places = placesWithRatings.slice(0, 5);
// Generate card elements dynamically
top5Places.forEach(place => {
const cardElement = document.createElement("li");
cardElement.className = "card";
cardElement.style.backgroundImage = `url('${place.photos[0]}')`;
cardElement.innerHTML = `
<div class="icon card-icon fas fa-star ${place.iconClass}"></div>
<h2>${place.title}</h2>
<span>Ratings: ${place.averageRating}</span>
`;
cardElement.addEventListener("click", () => {
window.top.location.href = `explore_cardcontent.php?id=${place.id}`;
});
carousel.appendChild(cardElement);
});
// Calculate card width, set initial positions, and add event listeners
const wrapper = document.querySelector(".wrapper");
const firstCardWidth = carousel.querySelector(".card").offsetWidth;
const arrowBtns = document.querySelectorAll(".wrapper i");
const carouselChildrens = [...carousel.children];
let isDragging = false,
isAutoPlay = true,
startX, startScrollLeft, timeoutId;
let cardPerView = Math.round(carousel.offsetWidth / firstCardWidth);
carouselChildrens.slice(-cardPerView).reverse().forEach(card => {
carousel.insertAdjacentHTML("afterbegin", card.outerHTML);
});
carouselChildrens.slice(0, cardPerView).forEach(card => {
carousel.insertAdjacentHTML("beforeend", card.outerHTML);
});
carousel.classList.add("no-transition");
carousel.scrollLeft = carousel.offsetWidth;
carousel.classList.remove("no-transition");
arrowBtns.forEach(btn => {
btn.addEventListener("click", () => {
carousel.scrollLeft += btn.id == "left" ? -firstCardWidth : firstCardWidth;
});
});
const dragStart = (e) => {
isDragging = true;
carousel.classList.add("dragging");
startX = e.pageX;
startScrollLeft = carousel.scrollLeft;
}
const dragging = (e) => {
if (!isDragging) return;
carousel.scrollLeft = startScrollLeft - (e.pageX - startX);
}
const dragStop = () => {
isDragging = false;
carousel.classList.remove("dragging");
}
const infiniteScroll = () => {
if (carousel.scrollLeft === 0) {
carousel.classList.add("no-transition");
carousel.scrollLeft = carousel.scrollWidth - (2 * carousel.offsetWidth);
carousel.classList.remove("no-transition");
}
else if (Math.ceil(carousel.scrollLeft) === carousel.scrollWidth - carousel.offsetWidth) {
carousel.classList.add("no-transition");
carousel.scrollLeft = carousel.offsetWidth;
carousel.classList.remove("no-transition");
}
clearTimeout(timeoutId);
if (!wrapper.matches(":hover")) autoPlay();
}
const autoPlay = () => {
if (window.innerWidth < 800 || !isAutoPlay) return;
timeoutId = setTimeout(() => carousel.scrollLeft += firstCardWidth, 2500);
}
autoPlay();
carousel.addEventListener("mousedown", dragStart);
carousel.addEventListener("mousemove", dragging);
document.addEventListener("mouseup", dragStop);
carousel.addEventListener("scroll", infiniteScroll);
wrapper.addEventListener("mouseenter", () => clearTimeout(timeoutId));
wrapper.addEventListener("mouseleave", autoPlay);
}
populateCarousel();
</script>
</body>
</html>