// ---------------------------DOM Elements & Variables--------------------------- const showAllBtn = document.getElementById("all-states-btn"); const noDistributors = document.getElementById("no-distributors"); const distributors = []; // -----------------------------------Classes----------------------------------- class Distributor { constructor(container) { this.container = container; this.stateId = container.dataset.stateId; this.header = this.container.querySelector(".beghelli__collap-header"); this.content = this.container.querySelector(".beghelli__collap-cont"); this.header.addEventListener("click", this.toggleCollapsible); this.toggleCollapsible(); } toggleCollapsible = () => { let icon = this.header.querySelector("i"); icon.classList.toggle("fa-chevron-up"); icon.classList.toggle("fa-chevron-down"); if(this.content.style.height == "" || this.content.style.height == "0px") { this.content.style.height = this.content.scrollHeight + "px"; } else { this.content.style.height = "0px"; } } applyFilter = (filterId) => { if(this.stateId == filterId) { this.container.classList.remove("hidden"); return true; } else { this.container.classList.add("hidden"); return false; } } show = () => this.container.classList.remove("hidden"); } // ----------------------------------Functions---------------------------------- const showDistributorsByState = stateId => { let stateFound = false; distributors.forEach(distributor => { let res = distributor.applyFilter(stateId); stateFound ||= res; }); noDistributors.style.display = stateFound ? "none" : "block"; showAllBtn.style.display = "flex"; } const showAllDistributors = () => { distributors.forEach(distributor => distributor.show()); showAllBtn.style.display = "none"; } const init = () => { // Initialize Leaflet map in México let map = L.map('map').setView([23.6345, -102.5528], 5); // México Coordinates // Load base map from OpenStreetMap L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }) .addTo(map); // Get Distributors Data let data = new FormData(); data.append("stateId", "allAsJson"); fetch("ajax/agentAjax.php", { method: "POST", body: data }) .then(res => res.json()) .then(json => { // Get distributors array for(item in json) { let id = json[item].stateId; let latitude = json[item].lat; let longitude = json[item].lon; let marker = L.marker([latitude, longitude]).addTo(map); marker.on("click", () => showDistributorsByState(id)); marker.bindPopup(json[item].stateName); } }) .catch(e => console.log(e)); // Create Distributors let _distributors = document.querySelectorAll(".state-collap"); _distributors.forEach(item => distributors.push(new Distributor(item)) ); } // -------------------------------Event Listeners------------------------------- window.addEventListener("load", init); showAllBtn.addEventListener("click", showAllDistributors);