Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <script>
- // URL de tu API de Google Sheets
- const API_URL = 'https://script.google.com/macros/s/AKfycbySaDGt9msgjKUWtWQhGIuPlA2DyM1QNe_r4JoEXikrjNRrql7guRHk_tBaBT9SY9e5DA/exec';
- let businesses = [];
- const itemsPerPage = 16;
- let currentPage = 1;
- let currentCategory = 'Todos';
- // Función para obtener los negocios desde Google Sheets
- async function fetchBusinessesFromGoogleSheets() {
- try {
- const response = await fetch(API_URL);
- const data = await response.json();
- return data.map(record => ({
- id: record.ID,
- name: record.Nombre,
- category: record.Categoria,
- description: record.Descripcion,
- fullDescription: record.DescripcionCompleta,
- image: record.ImagenURL,
- website: record.SitioWeb,
- mapUrl: record.MapaURL,
- social: record.RedesSociales,
- googleReviewsLink: record.GoogleReviewsLink || null,
- schedule: record.Horario,
- contact: record.Contacto,
- dateAdded: new Date(record.FechaAgregado),
- popularity: Number(record.Popularidad)
- }));
- } catch (error) {
- console.error('Error fetching data from Google Sheets:', error);
- return [];
- }
- }
- function removeAccents(str) {
- return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
- }
- function sortBusinesses(businesses, sortBy) {
- switch(sortBy) {
- case 'random':
- return businesses.sort(() => Math.random() - 0.5);
- case 'az':
- return businesses.sort((a, b) => a.name.localeCompare(b.name));
- case 'za':
- return businesses.sort((a, b) => b.name.localeCompare(a.name));
- case 'recent':
- return businesses.sort((a, b) => b.dateAdded - a.dateAdded);
- case 'popular':
- return businesses.sort((a, b) => b.popularity - a.popularity);
- default:
- return businesses;
- }
- }
- function renderBusinesses(page, category, searchTerm = '', sortBy = 'random') {
- const grid = document.getElementById('business-grid');
- grid.innerHTML = '';
- if (businesses.length === 0) {
- grid.innerHTML = '<div class="no-results-container"><div class="no-results">No hay negocios que mostrar.</div></div>';
- return;
- }
- const normalizedSearchTerm = removeAccents(searchTerm.toLowerCase());
- let filteredBusinesses = businesses.filter(business =>
- (category === 'Todos' || business.category.includes(category)) &&
- (removeAccents(business.name.toLowerCase()).includes(normalizedSearchTerm) ||
- business.category.some(cat => removeAccents(cat.toLowerCase()).includes(normalizedSearchTerm)) ||
- removeAccents(business.description.toLowerCase()).includes(normalizedSearchTerm) ||
- removeAccents(business.fullDescription.toLowerCase()).includes(normalizedSearchTerm))
- );
- filteredBusinesses = sortBusinesses(filteredBusinesses, sortBy);
- if (filteredBusinesses.length === 0) {
- grid.innerHTML = '<div class="no-results-container"><div class="no-results">No se encontraron resultados. Intenta buscar con otra palabra clave.</div></div>';
- return;
- }
- const start = (page - 1) * itemsPerPage;
- const end = start + itemsPerPage;
- const paginatedBusinesses = filteredBusinesses.slice(start, end);
- paginatedBusinesses.forEach(business => {
- const card = document.createElement('div');
- card.className = 'business-card';
- card.innerHTML = `
- <div class="category-label">${business.category.join(', ')}</div>
- <img src="${business.image}" alt="${business.name}">
- <div class="card-content">
- <h3>${business.name}</h3>
- <p>${business.description}</p>
- </div>
- `;
- card.onclick = () => showModal(business);
- grid.appendChild(card);
- });
- renderPagination(filteredBusinesses.length);
- updateActivePaginationButton(page);
- }
- function updateActivePaginationButton(page) {
- document.querySelectorAll('.pagination-button').forEach(btn => {
- btn.classList.remove('active');
- if (parseInt(btn.textContent) === page) {
- btn.classList.add('active');
- }
- });
- }
- function renderSortOptions() {
- const sortContainer = document.createElement('div');
- sortContainer.className = 'sort-options';
- sortContainer.innerHTML = `
- <label for="sort-select">Ordenar por:</label>
- <select id="sort-select">
- <option value="random">Aleatorio</option>
- <option value="az">A-Z</option>
- <option value="za">Z-A</option>
- <option value="recent">Más recientes</option>
- <option value="popular">Más populares</option>
- </select>
- `;
- document.querySelector('.ov-container').insertBefore(sortContainer, document.getElementById('business-grid'));
- document.getElementById('sort-select').addEventListener('change', function(e) {
- currentPage = 1;
- renderBusinesses(currentPage, currentCategory, document.getElementById('search').value, e.target.value);
- });
- }
- function scrollToTop() {
- const container = document.querySelector('.ov-container');
- container.scrollIntoView({ behavior: 'smooth', block: 'start' });
- }
- function renderPagination(totalItems) {
- const paginationContainer = document.getElementById('pagination');
- paginationContainer.innerHTML = '';
- const totalPages = Math.ceil(totalItems / itemsPerPage);
- for (let i = 1; i <= totalPages; i++) {
- const button = document.createElement('button');
- button.textContent = i;
- button.classList.add('pagination-button');
- if (i === currentPage) {
- button.classList.add('active');
- }
- button.onclick = () => {
- currentPage = i;
- renderBusinesses(currentPage, currentCategory);
- updateActivePaginationButton(currentPage);
- scrollToTop();
- };
- paginationContainer.appendChild(button);
- }
- }
- function renderCategories() {
- const categoriesContainer = document.getElementById('categories');
- categoriesContainer.innerHTML = '';
- let categories = ['Todos'];
- businesses.forEach(business => {
- business.category.forEach(cat => {
- if (!categories.includes(cat)) {
- categories.push(cat);
- }
- });
- });
- categories = ['Todos', ...categories.filter(c => c !== 'Todos').sort((a, b) => a.localeCompare(b))];
- categories.forEach(category => {
- const tab = document.createElement('button');
- tab.className = 'category-tab';
- tab.textContent = category;
- tab.onclick = () => {
- currentCategory = category;
- currentPage = 1;
- renderBusinesses(currentPage, currentCategory);
- document.querySelectorAll('.category-tab').forEach(t => t.classList.remove('active'));
- tab.classList.add('active');
- };
- categoriesContainer.appendChild(tab);
- });
- document.querySelector('.category-tab').classList.add('active');
- }
- function renderSocialMediaIcons(socialMedia) {
- const iconMap = {
- facebook: 'fab fa-facebook',
- instagram: 'fab fa-instagram',
- twitter: 'fab fa-twitter',
- youtube: 'fab fa-youtube',
- linkedin: 'fab fa-linkedin',
- pinterest: 'fab fa-pinterest',
- tiktok: 'fab fa-tiktok',
- delivery: 'fa-solid fa-truck-fast',
- whatsapp: 'fab fa-whatsapp'
- };
- if (!socialMedia || typeof socialMedia !== 'object' || Object.keys(socialMedia).length === 0) {
- return '';
- }
- return Object.entries(socialMedia).map(([platform, url]) => {
- const iconClass = iconMap[platform.toLowerCase()] || 'fas fa-link';
- return `<a href="${url}" target="_blank" title="${platform}"><i class="${iconClass}"></i></a>`;
- }).join('');
- }
- function renderContactInfo(contact) {
- const iconMap = {
- telefono: 'fas fa-phone',
- whatsapp: 'fab fa-whatsapp',
- direccion: 'fas fa-map-marker-alt',
- correo: 'fas fa-envelope'
- };
- if (!contact || (typeof contact === 'object' && Object.keys(contact).length === 0)) {
- return ''; // Retorna una cadena vacía si no hay datos de contacto
- }
- if (typeof contact === 'object' && contact !== null) {
- contact = Object.entries(contact)
- .map(([key, value]) => `${key}:${value}`)
- .join('; ');
- }
- if (typeof contact !== 'string' || contact.trim() === '') {
- return ''; // Retorna una cadena vacía si el contacto no es una cadena válida o está vacío
- }
- const contactItems = contact.split('; ');
- return contactItems.map(item => {
- const [type, value] = item.split(':');
- const iconClass = iconMap[type] || 'fas fa-address-book';
- let href, title;
- switch(type) {
- case 'telefono':
- href = `tel:${value}`;
- title = 'Llamar';
- break;
- case 'whatsapp':
- href = `https://wa.me/${value.replace(/[^0-9]/g, '')}`;
- title = 'Enviar mensaje de WhatsApp';
- break;
- case 'direccion':
- href = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(value)}`;
- title = 'Ver en Google Maps';
- break;
- case 'correo':
- href = `mailto:${value}`;
- title = 'Enviar correo electrónico';
- break;
- default:
- href = '#';
- title = type;
- }
- return `<a href="${href}" target="_blank" title="${title}"><i class="${iconClass}"></i> ${value}</a>`;
- }).join('<br>');
- }
- function adjustHeaderZIndex(zIndex) {
- const diviHeaders = [
- document.querySelector('header .et_builder_inner_content'),
- document.getElementById('main-header')
- ];
- diviHeaders.forEach(header => {
- if (header) {
- header.style.zIndex = zIndex;
- }
- });
- }
- function showModal(business) {
- const modal = document.getElementById('businessModal');
- const modalContent = document.getElementById('modalContent');
- const contactInfo = renderContactInfo(business.contact);
- modalContent.innerHTML = `
- <img src="${business.image}" alt="${business.name}" class="modal-image">
- <h2 class="modal-title">${business.name}</h2>
- <p class="modal-category">Categoría > ${business.category.join(', ')}</p>
- ${business.googleReviewsLink ? `
- <div class="google-reviews">
- <a href="${business.googleReviewsLink}" target="_blank" title="Ver reseñas en Google">
- <img src="https://demos.ovdivi.com/wp-content/uploads/2024/08/google-reviews.png" alt="Google Reviews" class="google-reviews-icon">
- </a>
- </div>
- ` : ''}
- <p class="modal-description">${business.fullDescription}</p>
- <div class="modal-links">
- ${business.website ? `<a href="${business.website}" target="_blank" title="Visitar sitio web"><i class="fas fa-globe"></i></a>` : ''}
- ${business.mapUrl ? `<a href="${business.mapUrl}" target="_blank" title="Ver en mapa"><i class="fas fa-map-marker-alt"></i></a>` : ''}
- ${renderSocialMediaIcons(business.social)}
- </div>
- ${business.schedule ? `
- <div class="modal-schedule">
- <h3><i class="far fa-clock"></i> Horario</h3>
- <p>${business.schedule}</p>
- </div>
- ` : ''}
- ${contactInfo ? `
- <div class="modal-contact">
- <h3><i class="fas fa-address-book"></i> Contacto</h3>
- ${contactInfo}
- </div>
- ` : ''}
- `;
- modal.style.display = 'block';
- adjustHeaderZIndex('0');
- }
- document.querySelector('.close').onclick = function() {
- document.getElementById('businessModal').style.display = 'none';
- adjustHeaderZIndex('0');
- }
- window.onclick = function(event) {
- if (event.target == document.getElementById('businessModal')) {
- document.getElementById('businessModal').style.display = 'none';
- adjustHeaderZIndex('0');
- }
- }
- document.addEventListener('keydown', function(event) {
- if (event.key === "Escape") {
- document.getElementById('businessModal').style.display = 'none';
- adjustHeaderZIndex('0');
- }
- });
- document.getElementById('search').addEventListener('input', function(e) {
- const searchTerm = e.target.value;
- currentPage = 1;
- renderBusinesses(currentPage, currentCategory, searchTerm);
- });
- // Función para mostrar y ocultar el precargador
- function showLoader() {
- document.getElementById('loader').style.display = 'flex';
- }
- function hideLoader() {
- document.getElementById('loader').style.display = 'none';
- }
- document.addEventListener('DOMContentLoaded', function () {
- const searchInput = document.getElementById('search');
- const clearIcon = document.getElementById('clear-icon');
- searchInput.addEventListener('input', function () {
- clearIcon.style.display = this.value ? 'block' : 'none';
- currentPage = 1;
- renderBusinesses(currentPage, currentCategory, this.value);
- });
- clearIcon.addEventListener('click', function () {
- searchInput.value = '';
- clearIcon.style.display = 'none';
- searchInput.focus();
- renderBusinesses(currentPage, currentCategory, '');
- });
- searchInput.addEventListener('keydown', function(event) {
- if (event.key === "Escape") {
- this.value = '';
- clearIcon.style.display = 'none';
- renderBusinesses(currentPage, currentCategory, '');
- }
- });
- });
- async function initializeDirectory() {
- showLoader();
- businesses = await fetchBusinessesFromGoogleSheets();
- hideLoader();
- if (businesses.length > 0) {
- renderCategories();
- renderSortOptions();
- renderBusinesses(currentPage, currentCategory, '', 'random');
- document.getElementById('sort-select').value = 'random';
- } else {
- document.getElementById('business-grid').innerHTML = '<div class="no-results">No hay negocios que mostrar.</div>';
- }
- }
- // Llamar a la función de inicialización cuando se carga la página
- document.addEventListener('DOMContentLoaded', initializeDirectory);
- </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement