Autocompletado de lugares con marcadores por estado
TO START, SELECT A COUNTRY
USA
CANADA
NOW, SELECT A STATE
Company
Phone
City
State
Actions
Advanced Search
Write any Zip Code,
Company Name, or
Address
you would like to search for
`;
return mobileSearchBarContent;
}
function injectMobileSearchBarContent() {
// Obtener el ancho de la pantalla
const screenWidth =
window.innerWidth || document.documentElement.clientWidth;
// Verificar si el ancho es menor a 1000px
if (screenWidth ({
Name: row.Name,
Phone: row.Phone,
City: row.City,
State: row.State,
Website: row.Website,
Address: row.Address,
}));
createTable(filteredRows, ["Name", "Phone", "City", "State"]);
},
error: function (error) {
console.error("Error al parsear el archivo CSV:", error);
},
});
} catch (error) {
console.error("Error al cargar el archivo CSV:", error);
}
}
// Modificar la función createTable para incluir atributos personalizados en las filas
function createTable(data, visibleColumns) {
const tableBody = document.getElementById("tableBody");
tableBody.innerHTML = ""; // Limpiar el contenido actual de la tabla antes de agregar nuevas filas
// Agregar el prefijo "+1" al número de teléfono utilizando map
const dataWithPrefix = data.map((row) => ({
...row,
Phone: "+1 " + row.Phone,
}));
dataWithPrefix.forEach((row, index) => {
// Verificar si al menos un valor significativo de la fila no es vacío, null o undefined
const hasSignificantValue = Object.values(row).some(
(value) =>
value && value !== "undefined" && value !== "" && value !== null
);
if (hasSignificantValue) {
const newRow = document.createElement("tr");
// Agregar atributos personalizados a la fila
newRow.setAttribute("data-name", row.Name || "");
newRow.setAttribute("data-phone", row.Phone || "");
newRow.setAttribute("data-website", row.Website || "");
newRow.setAttribute("data-address", row.Address || "");
visibleColumns.forEach((column, columnIndex) => {
const cellValue = row[column] || ""; // Obtener el valor de la columna o dejarlo vacío si es nulo o indefinido
const newCell = document.createElement("td");
newCell.textContent = cellValue;
newRow.appendChild(newCell);
if (columnIndex === 0) {
// Agregar la clase 'sticky' solo a la primera columna
newCell.classList.add("sticky");
}
});
newRow.innerHTML += `
`;
tableBody.appendChild(newRow);
updateButtonContent();
}
});
}
// Evento click para el botón "more info"
document.addEventListener("click", function (event) {
if (
event.target.classList.contains("moreInfoButton") ||
event.target.classList.contains("material-symbols-outlined")
) {
const row = event.target.closest("tr"); // Obtener la fila más cercana al botón clickeado
const name = row.getAttribute("data-name");
const address = row.getAttribute("data-address");
const phone = row.getAttribute("data-phone");
const website = row.getAttribute("data-website");
openModal(name, address, phone, website);
}
});
async function updateTableByState() {
const placeAbbreviations = {
Alabama: "AL",
Alaska: "AK",
Arizona: "AZ",
Arkansas: "AR",
California: "CA",
Colorado: "CO",
Connecticut: "CT",
Delaware: "DE",
Florida: "FL",
Georgia: "GA",
Hawaii: "HI",
Idaho: "ID",
Illinois: "IL",
Indiana: "IN",
Iowa: "IA",
Kansas: "KS",
Kentucky: "KY",
Louisiana: "LA",
Maine: "ME",
Maryland: "MD",
Massachusetts: "MA",
Michigan: "MI",
Minnesota: "MN",
Mississippi: "MS",
Missouri: "MO",
Montana: "MT",
Nebraska: "NE",
Nevada: "NV",
"New Hampshire": "NH",
"New Jersey": "NJ",
"New Mexico": "NM",
"New York": "NY",
"North Carolina": "NC",
"North Dakota": "ND",
Ohio: "OH",
Oklahoma: "OK",
Oregon: "OR",
Pennsylvania: "PA",
"Rhode Island": "RI",
"South Carolina": "SC",
"South Dakota": "SD",
Tennessee: "TN",
Texas: "TX",
Utah: "UT",
Vermont: "VT",
Virginia: "VA",
Washington: "WA",
"West Virginia": "WV",
Wisconsin: "WI",
Wyoming: "WY",
Alberta: "AB",
"British Columbia": "BC",
Manitoba: "MB",
"New Brunswick": "NB",
"Newfoundland and Labrador": "NL",
"Nova Scotia": "NS",
Ontario: "ON",
"Prince Edward Island": "PE",
Quebec: "QC",
Saskatchewan: "SK",
};
const tableState = placeAbbreviations[selectedState];
const selectedCity = document.getElementById("selectedCitySpan");
const selectedCountry = document.getElementById("selectedCountrySpan");
try {
const response = await fetch(
"https://viscosityoil.com/wp-content/uploads/2024/04/dealersMapCoordinatesv5.csv"
);
const csvData = await response.text();
// Utilizar Papa Parse para parsear el CSV correctamente
Papa.parse(csvData, {
header: true,
complete: function (results) {
const rows = results.data;
// Filtrar las filas según el estado seleccionado
let filteredStateRows = rows.filter(
(row) => row.State === tableState
);
if (
selectedState === "All States" ||
selectedState === "All provinces/territories"
) {
filteredStateRows = rows.filter(
(row) => row.Country === selectedCountry.textContent
);
}
// Crear la tabla con las filas filtradas
if (selectedCity.textContent === "All cities") {
createTable(filteredStateRows, [
"Name",
"Phone",
"City",
"State",
]);
}
},
error: function (error) {
console.error("Error al parsear el archivo CSV:", error);
},
});
} catch (error) {
console.error("Error al cargar el archivo CSV:", error);
}
}
// Ejecutar la función al cargar la página para inyectar el contenido de mobileSearchBar
window.addEventListener("load", injectMobileSearchBarContent);
let map;
let dealers = [];
const countriesDropdown = ["USA", "Canada"];
function selectCountry(country) {
onCountryChange(country);
updateButton();
}
// Función para cargar opciones de país
function loadCountries() {
const countryDropdown = document.getElementById("countryDropdown");
const countriesDropdown = ["USA", "Canada"];
// Iterar sobre el arreglo de países
countriesDropdown.forEach((country) => {
const option = document.createElement("a");
option.textContent = country;
option.onclick = () => selectCountryDropdown(country);
countryDropdown.appendChild(option);
});
}
function onCountryChange(country) {
const stateSelection = document.getElementById("stateSelection");
const selectedCountryDropdown = document.getElementById(
"selectedCountrySpan"
);
const stateSelectionHeaderText = document.getElementById(
"stateSelectionHeaderText"
);
const stateSelectionButtons = document.getElementById(
"stateSelectionButtons"
); // Get the container for state buttons
const countrySelection = document.getElementById("countrySelection");
if (country === "USA") {
let states = [
"All States",
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Kentucky",
"Louisiana",
"Maine",
"Maryland",
"Massachusetts",
"Michigan",
"Minnesota",
"Mississippi",
"Missouri",
"Montana",
"Nebraska",
"Nevada",
"New Hampshire",
"New Jersey",
"New Mexico",
"New York",
"North Carolina",
"North Dakota",
"Ohio",
"Oklahoma",
"Oregon",
"Pennsylvania",
"Rhode Island",
"South Carolina",
"South Dakota",
"Tennessee",
"Texas",
"Utah",
"Vermont",
"Virginia",
"Washington",
"West Virginia",
"Wisconsin",
"Wyoming",
];
states = states.sort(); // Order the states alphabetically
selectedCountryDropdown.textContent = "USA";
const stateButtons = states
.map(
(state) =>
``
)
.join("");
stateSelectionButtons.innerHTML = stateButtons; // Inject state buttons into the container
stateSelection.className = "usa";
stateSelectionButtons.className = "usa";
stateSelectionHeaderText.innerText = "SELECT A STATE";
countrySelection.style.display = "none";
stateSelection.style.display = "flex"; // Ensure the state selection container is visible
} else if (country === "Canada") {
selectedCountryDropdown.textContent = "Canada";
const provinces = [
"All provinces/territories",
"Alberta",
"British Columbia",
"Manitoba",
"New Brunswick",
"Newfoundland and Labrador",
"Nova Scotia",
"Ontario",
"Prince Edward Island",
"Quebec",
"Saskatchewan",
];
const provinceButtons = provinces
.map(
(province) =>
``
)
.join("");
stateSelectionButtons.innerHTML = provinceButtons;
stateSelection.className = "canada";
stateSelectionButtons.className = "canada";
stateSelectionHeaderText.innerHTML = "SELECT A TERRITORY/PROVINCE";
countrySelection.style.display = "none"; // Inject province buttons into the container
stateSelection.style.display = "flex"; // Ensure the state selection container is visible
}
}
function goBackToCountrySelection() {
const stateSelection = document.getElementById("stateSelection");
const countrySelection = document.getElementById("countrySelection");
// Hide state selection and show country selection
stateSelection.style.display = "none";
countrySelection.style.display = "flex";
clearCountries();
}
function clearCountries() {
const countryDropdown = document.getElementById("countryDropdown");
// Eliminar todos los hijos de countryDropdown
while (countryDropdown.firstChild) {
countryDropdown.removeChild(countryDropdown.firstChild);
}
}
function showMap(location) {
const selectedCountrySpan = document.getElementById(
"selectedCountrySpan"
);
const state = selectedState;
const country = selectedCountrySpan.textContent;
document.getElementById("backgroundContainer").style.display = "none";
// Show the map container
document.getElementById("mapContainer").style.display = "flex";
// Initialize the map centered on the selected location
initMap(location, country);
// Hide the state selection container
document.getElementById("stateSelection").style.display = "none";
}
function initMap(location, country) {
// Create a geocoder object
const geocoder = new google.maps.Geocoder();
let zoom = 7;
if (
location === "All States" ||
location === "All provinces/territories"
) {
zoom = 4;
}
// Geocode the location to get its coordinates
const address = location + ", " + country; // Combinar estado y país para la búsqueda
geocoder.geocode({ address: address }, function (results, status) {
if (status === "OK") {
// Create a map centered on the geocoded location
map = new google.maps.Map(document.getElementById("map"), {
center: results[0].geometry.location,
zoom: zoom,
streetViewControl: false,
});
// Load the dealers' data from the CSV file
loadDealersCSV(location);
}
// } else {
// alert('Geocode was not successful for the following reason: ' + status);
// }
});
}
let allMarkers = [];
function loadDealersCSV(stateName) {
const placeAbbreviations = {
Alabama: "AL",
Alaska: "AK",
Arizona: "AZ",
Arkansas: "AR",
California: "CA",
Colorado: "CO",
Connecticut: "CT",
Delaware: "DE",
Florida: "FL",
Georgia: "GA",
Hawaii: "HI",
Idaho: "ID",
Illinois: "IL",
Indiana: "IN",
Iowa: "IA",
Kansas: "KS",
Kentucky: "KY",
Louisiana: "LA",
Maine: "ME",
Maryland: "MD",
Massachusetts: "MA",
Michigan: "MI",
Minnesota: "MN",
Mississippi: "MS",
Missouri: "MO",
Montana: "MT",
Nebraska: "NE",
Nevada: "NV",
"New Hampshire": "NH",
"New Jersey": "NJ",
"New Mexico": "NM",
"New York": "NY",
"North Carolina": "NC",
"North Dakota": "ND",
Ohio: "OH",
Oklahoma: "OK",
Oregon: "OR",
Pennsylvania: "PA",
"Rhode Island": "RI",
"South Carolina": "SC",
"South Dakota": "SD",
Tennessee: "TN",
Texas: "TX",
Utah: "UT",
Vermont: "VT",
Virginia: "VA",
Washington: "WA",
"West Virginia": "WV",
Wisconsin: "WI",
Wyoming: "WY",
Alberta: "AB",
"British Columbia": "BC",
Manitoba: "MB",
"New Brunswick": "NB",
"Newfoundland and Labrador": "NL",
"Nova Scotia": "NS",
Ontario: "ON",
"Prince Edward Island": "PE",
Quebec: "QC",
Saskatchewan: "SK",
};
// Obtener la abreviatura del estado a partir de su nombre
const stateAbbreviation = placeAbbreviations[stateName];
const selectedCountry = document.getElementById("selectedCountrySpan");
fetch(
"https://viscosityoil.com/wp-content/uploads/2024/04/dealersMapCoordinatesv5.csv"
)
.then((response) => response.text())
.then((text) => {
// Parse the CSV data using PapaParse
let parsedData = Papa.parse(text, {
header: true,
transform: function (value, header) {
// Eliminar las comillas de los valores de State y Website
if (
header === "State" ||
header === "Website" ||
header === "Coordinates"
) {
return value.replace(/["{}]/g, "");
} else {
return value;
}
},
}).data;
allMarkers = parsedData;
// Filtrar los datos del CSV por la abreviatura del estado
let filteredData = parsedData.filter((row) => {
// Obtener la abreviatura del estado en el CSV y convertirla a mayúsculas
const csvStateAbbreviation = row["State"];
// Comparar la abreviatura del estado en el CSV con la abreviatura del estado seleccionado
return csvStateAbbreviation === stateAbbreviation;
});
if (
stateName === "All States" ||
stateName === "All provinces/territories"
) {
filteredData = parsedData.filter((row) => {
const country = row["Country"];
return country === selectedCountry.textContent;
});
}
// Process each filtered row and create a marker for each dealer
filteredData.forEach((row) => {
let name = row["Name"];
let address = row["Address"];
let phone = row["Phone"];
let website = row["Website"];
let coordinates = row["Coordinates"];
let city = row["City"];
// Geocode the dealer's address to get its coordinates
coordinates = coordinates.replace(/\{|\}/g, "");
createMarkers(name, address, phone, website, coordinates);
});
})
.catch((error) => console.error("Error fetching CSV file:", error));
}
let currentMarkers = [];
function createMarkers(name, address, phone, website, coordinates, city) {
if (coordinates === undefined) {
console.error("coordinates es undefined");
return; // Salir de la función si coordinates es undefined
}
// Agregar el prefijo "+1" al número de teléfono
const phoneWithPrefix = "+1 " + phone;
// Dividir las coordenadas en latitud y longitud
const [lat, lng] = coordinates.split(", ");
// Crear un objeto LatLng con las coordenadas
const position = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng)
);
// Crear un marcador para el distribuidor
let marker = new google.maps.Marker({
map: map,
position: position,
title: name,
});
marker.setMap(map);
currentMarkers.push(marker);
// Agregar evento click al marcador para abrir el modal
marker.addListener("click", function () {
openModal(name, address, phoneWithPrefix, website);
});
}
let userLocation;
// const Swal = require("sweetalert2");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
userLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
},
function (error) {
var errorMessage = "Error getting location: ";
switch (error.code) {
case error.PERMISSION_DENIED:
errorMessage += "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
errorMessage += "Location information is unavailable.";
break;
case error.TIMEOUT:
errorMessage += "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
errorMessage += "An unknown error occurred.";
break;
}
console.error(errorMessage);
// Puedes mostrar el mensaje de error en la interfaz de usuario
alert(errorMessage);
}
);
} else {
console.log("Error getting user location");
// Puedes mostrar un mensaje de error en la interfaz de usuario
alert(
"Error getting user location: Geolocation is not supported by this browser."
);
}
let markersArray = [];
function findNearestDealers(userLocation) {
const selectedCountrySpan = document.getElementById(
"selectedCountrySpan"
);
const selectedStateSpan = document.getElementById("selectedState");
const selectedCitySpan = document.getElementById("selectedCitySpan");
if (!userLocation) return;
let nearestMarker = null;
let nearestMarkerState = null;
let nearestDistance = Infinity;
const maxDistanceMiles = 50; // Máximo rango de búsqueda en millas
markersArray = [];
allMarkers.forEach((markerData) => {
if (!markerData.Coordinates) return; // Ignorar marcadores sin coordenadas
// Convertir las coordenadas de texto a objetos { lat, lng }
let [lat, lng] = markerData.Coordinates.split(", ");
if (isNaN(lat) || isNaN(lng)) return; // Ignorar coordenadas inválidas
let markerPosition = {
lat: parseFloat(lat),
lng: parseFloat(lng),
};
let distance = google.maps.geometry.spherical.computeDistanceBetween(
userLocation,
markerPosition
);
if (distance {
if (!markerData.Coordinates) return; // Ignorar marcadores sin coordenadas
// Convertir las coordenadas de texto a objetos { lat, lng }
let [lat, lng] = markerData.Coordinates.split(", ");
if (isNaN(lat) || isNaN(lng)) return; // Ignorar coordenadas inválidas
let markerPosition = {
lat: parseFloat(lat),
lng: parseFloat(lng),
};
let distance =
google.maps.geometry.spherical.computeDistanceBetween(
userLocation,
markerPosition
);
if (distance {
if (index === buttonIndex) {
button.classList.add("active");
map.style.display = "none";
table.style.display = "flex";
} else {
button.classList.remove("active");
table.style.display = "none";
map.style.display = "flex";
}
});
}
function searchOptionsButton() {
const button = document.querySelector(".searchOptionsButton");
const searchOptionsOpen = document.querySelector(".searchOptionsOpen");
if (button.classList.contains("active")) {
button.classList.remove("active");
searchOptionsOpen.style.display = "none";
} else {
button.classList.add("active");
searchOptionsOpen.style.display = "flex";
}
}
const countries = {
USA: [
"All States",
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Kentucky",
"Louisiana",
"Maine",
"Maryland",
"Massachusetts",
"Michigan",
"Minnesota",
"Mississippi",
"Missouri",
"Montana",
"Nebraska",
"Nevada",
"New Hampshire",
"New Jersey",
"New Mexico",
"New York",
"North Carolina",
"North Dakota",
"Ohio",
"Oklahoma",
"Oregon",
"Pennsylvania",
"Rhode Island",
"South Carolina",
"South Dakota",
"Tennessee",
"Texas",
"Utah",
"Vermont",
"Virginia",
"Washington",
"West Virginia",
"Wisconsin",
"Wyoming",
],
Canada: [
"All provinces/territories",
"Alberta",
"British Columbia",
"Manitoba",
"New Brunswick",
"Newfoundland and Labrador",
"Nova Scotia",
"Ontario",
"Prince Edward Island",
"Quebec",
"Saskatchewan",
],
};
// Función para cargar opciones de estado
function loadStates(country) {
const stateDropdown = document.getElementById("stateDropdown");
stateDropdown.innerHTML = ""; // Limpiar opciones anteriores
countries[country].forEach((state) => {
const option = document.createElement("a");
option.textContent = state;
option.onclick = () => selectState(state); // Agregar evento onclick para seleccionar el estado
stateDropdown.appendChild(option);
});
}
/// Variable global para almacenar el estado seleccionado
let selectedState = "";
let selectedCountry = "";
function selectedCountryDropdown(country) {
const selectedCountrySpan = document.getElementById("selectedCountry");
selectedStateSpan.textContent = country;
}
// Función para seleccionar un estado y mostrarlo en el dropdown
function selectState(state) {
selectedState = state;
const selectedStateSpan = document.getElementById("selectedState");
const selectedCitySpan = document.getElementById("selectedCitySpan");
selectedStateSpan.textContent = state;
selectedCitySpan.textContent = "All cities";
updateCityOptions();
}
let markersArrayTable = [];
// Función para buscar la ubicación seleccionada
function searchLocation() {
const selectedCountrySpan = document.getElementById(
"selectedCountrySpan"
);
const state = selectedState;
const country = selectedCountrySpan.textContent;
if (
selectedCity === "All cities" &&
state !== "All States" &&
state !== "All provinces/territories"
) {
showMap(state);
initMap(state, country);
} else {
clearMarkers();
const placeAbbreviations = {
Alabama: "AL",
Alaska: "AK",
Arizona: "AZ",
Arkansas: "AR",
California: "CA",
Colorado: "CO",
Connecticut: "CT",
Delaware: "DE",
Florida: "FL",
Georgia: "GA",
Hawaii: "HI",
Idaho: "ID",
Illinois: "IL",
Indiana: "IN",
Iowa: "IA",
Kansas: "KS",
Kentucky: "KY",
Louisiana: "LA",
Maine: "ME",
Maryland: "MD",
Massachusetts: "MA",
Michigan: "MI",
Minnesota: "MN",
Mississippi: "MS",
Missouri: "MO",
Montana: "MT",
Nebraska: "NE",
Nevada: "NV",
"New Hampshire": "NH",
"New Jersey": "NJ",
"New Mexico": "NM",
"New York": "NY",
"North Carolina": "NC",
"North Dakota": "ND",
Ohio: "OH",
Oklahoma: "OK",
Oregon: "OR",
Pennsylvania: "PA",
"Rhode Island": "RI",
"South Carolina": "SC",
"South Dakota": "SD",
Tennessee: "TN",
Texas: "TX",
Utah: "UT",
Vermont: "VT",
Virginia: "VA",
Washington: "WA",
"West Virginia": "WV",
Wisconsin: "WI",
Wyoming: "WY",
Alberta: "AB",
"British Columbia": "BC",
Manitoba: "MB",
"New Brunswick": "NB",
"Newfoundland and Labrador": "NL",
"Nova Scotia": "NS",
Ontario: "ON",
"Prince Edward Island": "PE",
Quebec: "QC",
Saskatchewan: "SK",
};
let stateAbbrev = placeAbbreviations[selectedState];
let cityMarkers = allMarkers.filter((markerData) => {
return (
markerData.State === stateAbbrev &&
markerData.City === selectedCity
);
});
if (state === "All States" || state === "All provinces/territories") {
cityMarkers = allMarkers.filter((markerData) => {
return markerData.Country === country;
});
}
if (
cityMarkers.length === 0 &&
state !== "All States" &&
state !== "All provinces/territories"
) {
Swal.fire({
title: "No dealers found",
text: "No dealers found for the selected city",
icon: "info",
confirmButtonText: "Close",
animation: true,
width: "20%",
position: "center",
customClass: {
title: "swal2-title-custom",
popup: "swal2-popup-custom",
confirmButton: "swal2-confirm-button-custom",
},
});
} else {
markersArrayTable = [];
let index = 0;
let divideInto = 1;
if (cityMarkers.length > 100) {
divideInto = 6;
}
const chunkSize = Math.ceil(cityMarkers.length / divideInto);
function processChunk() {
const chunkEnd = Math.min(index + chunkSize, cityMarkers.length);
for (; index 40) {
if (country === "USA") {
map.setCenter({
lat: 39.770034006706446,
lng: -101.39999772388677,
});
setTimeout(function () {
map.setZoom(3.5); // Primero, haz zoom out
setTimeout(function () {
map.setZoom(4); // Luego, después de otro retraso, haz zoom in
}, 1000);
}, 3000);
} else if (country === "Canada") {
map.setCenter({
lat: 49.213264092705636,
lng: -96.95193426597235,
});
setTimeout(function () {
map.setZoom(3.5); // Primero, haz zoom out
setTimeout(function () {
map.setZoom(4); // Luego, después de otro retraso, haz zoom in
}, 1000);
}, 1000);
}
}
}
}
}
// Función para seleccionar un país
function selectCountryDropdown(country) {
loadStates(country);
document.getElementById("countryDropdownContainer").style.display =
"flex";
const stateLabel = document.getElementById("stateLabel");
selectedCountry = country;
const selectedCountrySpan = document.getElementById(
"selectedCountrySpan"
);
selectedCountrySpan.textContent = country;
if (selectedCountrySpan.textContent === "USA") {
stateLabel.innerText = "* State";
}
if (selectedCountrySpan.textContent === "Canada") {
stateLabel.innerText = "* Province/Territory";
}
}
// Llamamos a la función para cargar los países al iniciar
function toggleDropdown(dropdownId) {
const dropdownContent = document.getElementById(dropdownId);
const selectedCountrySpan = document.getElementById(
"selectedCountrySpan"
);
const countryDropdown = document.querySelector(".countryDropbtn");
const stateDropdown = document.querySelector(".stateDropbtn");
if (
selectedCountrySpan !== "Select Country" ||
selectedCountrySpan == null
) {
stateDropdown.disabled = false;
}
if (countryDropdown.classList.contains("active")) {
countryDropdown.classList.remove("active");
} else {
countryDropdown.classList.add("active");
}
dropdownContent.classList.toggle("show");
}
function toggleDropdownState(dropdownId) {
const dropdownContent = document.getElementById(dropdownId);
const selectedCountrySpan = document.getElementById(
"selectedCountrySpan"
);
const selectedStateSpan = document.getElementById("selectedState");
const cityDropdown = document.querySelector(".cityDropbtn");
const stateDropdown = document.querySelector(".stateDropbtn");
if (selectedStateSpan !== "Select State" || selectedStateSpan == null) {
cityDropdown.disabled = false;
}
if (selectedCountrySpan.textContent === "Select Country") {
stateDropdown.disabled = true;
return;
} else {
dropdownContent.classList.toggle("show");
}
if (stateDropdown.classList.contains("active")) {
stateDropdown.classList.remove("active");
} else {
stateDropdown.classList.add("active");
}
}
function toggleDropdownCity(dropdownId) {
const dropdownContent = document.getElementById(dropdownId);
const selectedStateSpan = document.getElementById("selectedState");
const cityDropdown = document.querySelector(".cityDropbtn");
if (selectedStateSpan.textContent === "Select State") {
cityDropdown.disabled = true;
return;
} else {
dropdownContent.classList.toggle("show");
}
if (cityDropdown.classList.contains("active")) {
cityDropdown.classList.remove("active");
} else {
cityDropdown.classList.add("active");
}
}
function dropdownOpen(dropdownId) {
const countryDropdownButton = document.getElementById(dropdownId);
countryDropdownButton.classList.toggle("open");
}
// Close the dropdown menu if the user clicks outside of it
window.addEventListener("click", function (event) {
if (!event.target.matches(".stateDropbtn")) {
const stateDropdowns = document.getElementsByClassName(
"stateDropdown-content"
);
const stateDropdownButton = document.querySelector(".stateDropbtn");
if (stateDropdownButton.classList.contains("active")) {
stateDropdownButton.classList.remove("active");
}
for (let i = 0; i ';
const sortIconDown = '';
const sortDefault = '';
let sortBy = ""; // Variable para almacenar la columna por la que se está ordenando
let sortOrder = ""; // Variable para almacenar el orden ascendente o descendente
function sortTable(columnIndex) {
const table = document.getElementById("tableBody");
const rows = Array.from(table.rows);
// Determinar la dirección de ordenamiento
if (sortBy === columnIndex) {
sortOrder = sortOrder === "asc" ? "desc" : "asc";
} else {
sortBy = columnIndex;
sortOrder = "asc";
}
// Ordenar las filas según la columna y dirección de ordenamiento
rows.sort((a, b) => {
const textA = a.cells[columnIndex].textContent.trim().toLowerCase();
const textB = b.cells[columnIndex].textContent.trim().toLowerCase();
if (sortOrder === "asc") {
return textA.localeCompare(textB);
} else {
return textB.localeCompare(textA);
}
});
// Actualizar la tabla con las filas ordenadas
table.innerHTML = ""; // Limpiar la tabla antes de agregar las filas ordenadas
rows.forEach((row) => table.appendChild(row));
// Actualizar el ícono de filtro en el encabezado de la columna ordenada
updateSortIcon(columnIndex);
}
function updateSortIcon(columnIndex) {
if (columnIndex !== 4) {
// Verificar si no es la columna "Actions"
// Actualizar el ícono de filtro en la columna ordenada
clearSortIcons();
const header = document.querySelectorAll("th")[columnIndex];
const spanElement = header.querySelector("span");
if (spanElement) {
// Limpiar cualquier icono de ordenamiento existente en el span
const existingIcon = spanElement.querySelector("i");
if (existingIcon) {
spanElement.removeChild(existingIcon);
}
// Agregar el nuevo ícono de ordenamiento
const iconElement = document.createElement("i");
iconElement.className =
sortOrder === "asc"
? "fas fa-sort-alpha-up"
: "fas fa-sort-alpha-down";
spanElement.appendChild(iconElement);
}
}
}
function clearSortIcons() {
const headers = document.querySelectorAll("th");
headers.forEach((header, index) => {
if (index !== 4) {
// Excluir la columna "Actions" (suponiendo que es la quinta columna, es decir, el índice 4)
const spanElement = header.querySelector("span");
if (spanElement) {
// Limpiar cualquier icono de ordenamiento existente en el span
const existingIcon = spanElement.querySelector("i");
if (existingIcon) {
spanElement.removeChild(existingIcon);
}
// Agregar el ícono de ordenamiento predeterminado (hacia abajo)
const iconElement = document.createElement("i");
iconElement.className = "fas fa-sort";
spanElement.appendChild(iconElement);
}
}
});
// Agregar la lógica de cambio de icono basado en el tamaño de la pantalla
const originalIcon = document.querySelector(".fa-sort");
const smallScreenIcon = document.querySelector(".fa-sort-small-screen");
if (originalIcon && smallScreenIcon) {
changeIconBasedOnScreenSize();
window.addEventListener("resize", () => {
changeIconBasedOnScreenSize();
});
}
function changeIconBasedOnScreenSize() {
const screenWidth = window.innerWidth;
if (screenWidth {
if (screenWidth info';
} else {
button.innerHTML =
'More info';
}
});
}
window.addEventListener("load", updateButtonContent);
window.addEventListener("resize", updateButtonContent);
document
.getElementById("findNearestButton")
.addEventListener("click", function () {
findNearestDealers(userLocation); // Llama a la función findNearestDealers con la ubicación del usuario
});
// Agregar evento de escucha al formulario de búsqueda
// let matchesSearchTextMap;
// searchForm.addEventListener("submit", function (event) {
// event.preventDefault(); // Evitar que se recargue la página al enviar el formulario
// const searchInput = document.getElementById("searchInput");
// const searchText = searchInput.value.trim().toLowerCase(); // Obtener el texto de búsqueda y limpiarlo
// const searchNotFound = document.getElementById("inputLabelBelow");
// const modalSearch = document.getElementById("searchModal");
// const overlay = document.getElementById("overlay");
// const selectedCountrySpan = document.getElementById(
// "selectedCountrySpan"
// );
// const selectedStateSpan = document.getElementById("selectedState");
// if (searchText !== "") {
// //FILTER FOR TABLE
// // Filtrar las filas de la tabla según el texto de búsqueda en minúsculas
// const filteredRows = allRows.filter((row) => {
// const company = row.Company ? row.Company.toLowerCase() : ""; // Convertir a minúsculas si company no es undefined
// const zipcode = row.Zipcode ? row.Zipcode.toLowerCase() : ""; // Convertir a minúsculas si zipcode no es undefined
// const address = row.Address ? row.Address.toLowerCase() : ""; // Convertir a minúsculas si address no es undefined
// const website = row.Website ? row.Website.toLowerCase() : ""; // Convertir a minúsculas si website no es undefined
// const phone = row.Phone ? row.Phone.toLowerCase() : ""; // Convertir a minúsculas si phone no es undefined
// // Verificar si alguna columna coincide con el texto de búsqueda en minúsculas
// const matchesSearchText =
// (company && company.includes(searchText)) ||
// (zipcode && zipcode.includes(searchText)) ||
// (address && address.includes(searchText));
// return matchesSearchText;
// });
// //FILTER FOR MAPS
// // Filtrar las filas de la tabla según el texto de búsqueda en minúsculas
// const filteredRowsMap = allMarkers.filter((row) => {
// const company = row.Company ? row.Company.toLowerCase() : ""; // Convertir a minúsculas si company no es undefined
// const zipcode = row.Zipcode ? row.Zipcode.toLowerCase() : ""; // Convertir a minúsculas si zipcode no es undefined
// const address = row.Address ? row.Address.toLowerCase() : ""; // Convertir a minúsculas si address no es undefined
// const website = row.Website ? row.Website.toLowerCase() : ""; // Convertir a minúsculas si website no es undefined
// const phone = row.Phone ? row.Phone.toLowerCase() : ""; // Convertir a minúsculas si phone no es undefined
// const city = row.City ? row.City.toLowerCase() : "";
// // Verificar si alguna columna coincide con el texto de búsqueda en minúsculas
// const matchesSearchTextMap =
// (company && company.includes(searchText)) ||
// (zipcode && zipcode.includes(searchText)) ||
// (city && city.includes(searchText));
// return matchesSearchTextMap;
// });
// if (filteredRows.length > 0 && filteredRowsMap.length > 0) {
// modalSearch.style.display = "none";
// overlay.style.display = "none";
// // Obtener la primera dirección que hace match
// const firstMatchAddress = filteredRows[0].Address; // Suponiendo que el address es la dirección a geocodificar
// // Iniciar el mapa centrado en la primera dirección que hace match
// clearMarkers();
// selectedCountry = "";
// selectedState = "";
// selectedStateSpan.textContent = "Select State";
// selectedCountrySpan.textContent = "Select Country";
// // Llamar a la función para geocodificar la dirección de cada distribuidor que hace match
// filteredRowsMap.forEach((row) => {
// const { Name, Address, Phone, Website, Coordinates, City } = row;
// createMarkers(Name, Address, Phone, Website, Coordinates, City);
// });
// // Crear las filas de la tabla con los resultados de la búsqueda
// tableBody = document.getElementById("tableBody");
// tableBody.innerHTML = ""; // Limpiar el contenido actual de la tabla antes de agregar nuevas filas
// createTable(filteredRows, ["Company", "Phone", "City", "State"]);
// } else {
// searchNotFound.style.display = "flex";
// console.log("No results");
// }
// } else {
// console.log("Search text is empty.");
// }
// });
function clearMarkers() {
for (let markerKey in currentMarkers) {
if (Object.prototype.hasOwnProperty.call(currentMarkers, markerKey)) {
const marker = currentMarkers[markerKey];
// Verificar si el marcador tiene un método setMap y llamarlo para eliminar el marcador del mapa
if (marker) {
marker.setMap(null);
}
} else {
console.log("No setmap function");
}
}
}
let selectedCity;
function updateCityOptions() {
const selectedState = document.getElementById("selectedState");
const state = selectedState.textContent;
selectedCity = "All cities";
const citiesByState = {
Alberta: ["Camrose", "Wetaskiwin", "Brooks", "Claresholm", "Taber"],
"British Columbia": ["Surrey", "Kamloops", "Courtenay", "Duncan"],
Manitoba: ["Winnipeg"],
"New Brunswick": [
"Dalhousie Junction",
"Bathurst",
"Edmundston",
"Sussex East",
"Saint-Isidore",
"Grand Falls",
"Berry Mills",
],
Ontario: [
"Coldwater",
"Brantford",
"Kichener",
"Brantford",
"Jarvis",
"Cookstown",
"Erin",
"Delhi",
"Wallenstein",
"Burgessville",
"Alliston",
"Charlottetown",
"Hensall",
"Mount Forest",
"Binbrook",
"Barrie",
],
"Prince Edward Island": ["Norwich", "York"],
Quebec: [
"Montmagny",
"St-Joseph-De-Beauce",
"Matane",
"Saint-Esprit",
"Saint-Georges",
"Matane",
"Mercier",
"Saint-Esprit",
"Sainte-Marie",
],
Saskatchewan: [
"Moose Jaw",
"Switft Current",
"Saskatoon",
"Unity",
"Davidson",
"Windthorst",
"Watrous",
"Moose Jaw",
"Chamberlain",
"Assiniboia",
"Weyburn",
"Raymore",
],
Indiana: ["Huntingburg"],
Maryland: ["Warwick"],
Pennsylvania: ["Lititz"],
Arkansas: [
"Augusta",
"Atkins",
"Mabelvale",
"Springdale",
"Texarkana",
"Berryville",
"Rogers",
"Springdale",
"Cabot",
"Searcy",
"Pocahontas",
],
Arizona: ["Thatcher", "Maricopa", "Buckeye", "Coolidge"],
Colorado: [
"Greeley",
"Fort Morgan",
"Sterling",
"Fort Collins",
"Longmont",
],
Delaware: ["Seaford"],
Georgia: ["Blackshear", "Thomas", "Waynesboro", "Hattiesburg"],
Iowa: [
"Alta",
"Arthur",
"Bancroft",
"Ottumwa",
"St. Olaf",
"Sheffield",
"Ruthven",
"Sully",
"Clear Lake",
"Carroll",
"Council Bluffs",
"Osceola",
"Elkhart",
"Grand Junction",
"Sioux City",
"Dyersville",
"Monticello",
"Williamsburg",
"Orange City",
"Rock Valley",
"Atlantic",
"Albia",
"Cushing",
],
Idaho: [
"Caldwell",
"Twin Falls",
"Boise",
"Twin Falls",
"Nampa",
"Grace",
"Preston",
],
Illinois: [
"Pittsfield",
"Albion",
"Atlanta",
"Farmer City",
"Clinton",
"Mason City",
"Teutopolis",
],
Indiana: [
"West College Corner",
"Logansport",
"Rossville",
"Gas City",
"Huntington",
"Topeka",
"Rushville",
"Palmyra",
"Brookville",
],
Kansas: [
"Thayer",
"Iola",
"Washington",
"Hoxie",
"South Hutchinson",
"Dodge City",
"Wamego",
"Great Bend",
"Wichita",
"Ottawa",
"Ellsworth",
"Garden City",
"Hays",
"Wakeeney",
],
Kentucky: [
"Morganfield",
"Russellville",
"Hopkinsville",
"Owensboro",
"Murray",
"Bowling Green",
"Columbia",
"Somerset",
"London",
],
Louisiana: [
"Welsh",
"Abbeville",
"Lake Charles",
"Baton Rouge",
"Donaldsonville",
"Houma",
"Broussard",
"Monroe",
"St. Rose",
"Alexandria",
"Mandeville",
"Shreveport",
],
Massachusetts: ["South Dennis"],
Maryland: ["Churchville"],
Maine: ["Sabattus"],
Michigan: [
"Lennon",
"Wayland",
"Dowagiac",
"Bridgeport",
"Carlton",
"North Branch",
"Ithaca",
"Mc Bain",
"Tustin",
"Benton Harbor",
"Manchester",
"Pigeon",
"Bad Axe",
"Adrian",
"Fremont",
"Sandusky",
"Litchfield",
"West Branch",
"Charlotte",
],
Minnesota: [
"Alden",
"Glencoe",
"Kimball",
"Mankato",
"St. Cloud",
"St. Martin",
"Willmar",
"Pine Island",
"Fairmount",
"Slayton",
"Sleepy Eye",
"Bingham Lake",
"Hastings",
"Adams",
"Northfield",
"Plainfield",
"Kasson",
"Granite Falls",
],
Missouri: [
"Savannah",
"Appleton City",
"Ste Genevieve",
"Nevada",
"Harrisonville",
"Lamar",
"Cameron",
"Cameron",
"Lawson",
"Charleston",
"Sikeston",
"Mountain Grove",
"Lebanon",
"Branson",
"Joplin",
"Rogersville",
"Lockwood",
"Marysville",
"Kansas City",
"Hermann",
"Gallatin",
"Baring",
"Wright City",
"Hannibal",
],
Mississippi: [
"Greenwood",
"Yazoo City",
"Leland",
"Cleveland",
"Columbia",
"Magee",
"Jackson",
],
Montana: [
"Conrad",
"Helena",
"Great Falls",
"Lewistown",
"St Ignatius",
"Jackson",
"Dillon",
"Ethridge",
"Billings",
"Kalispell",
"Hysham",
"Havre",
"Great Falls",
"Billings",
"Glasgow",
"Belgrade",
"Missoula",
"Sidney",
"Scobey",
"Broadus",
],
"North Carolina": [
"Goldsboro",
"Siller City",
"Graham",
"Williamston",
"Newton",
"Union Grove",
],
"North Dakota": [
"Grafton",
"Cavalier",
"Watford City",
"Harvey",
"Carrington",
"Devils Lake",
],
Nebraska: [
"David City",
"Humboldt",
"Schuyler",
"Lincoln",
"Crofton",
"Neligh",
"Albion",
"Syracuse",
"West Point",
"York",
"Lodgepole",
],
"New Jersey": ["Bridgeton"],
Nevada: ["Sparks"],
"New York": [
"Montgomery",
"Stamford",
"Cochecton",
"Amsterdam",
"Lockport",
"Fultonville",
"Canastota",
"Franklin",
"Lowville",
"Schaghticoke",
"Waterville",
],
Ohio: [
"Maumee",
"Akron",
"Covington",
"Mechanicsburg",
"Botkins",
"Washington Court House",
"Ashland",
"Seaman",
"Cortland",
"Bucyrus",
"Fort Recovery",
"Gallipolis",
"Wellington",
"Wooster",
"Ridgeville Corners",
"North Star",
"Ottawa",
"Portage",
"Bellevue",
"Sherwood",
"Archbold",
"Eaton",
"Sterling",
"Findlay",
"Fremont",
"Thompson",
],
Oklahoma: ["Clinton", "Oklahoma City"],
Oregon: ["The Dalles", "La Grande", "Hermiston"],
Pennsylvania: [
"Elizabethtown",
"Leola",
"Richland",
"Waynesboro",
"Cogan Station",
"New Ringgold",
"Honesdale",
"New Bethlehem",
"Grove City",
"Mount Joy",
"Carlisle",
"Aspers",
"Halifax",
"Abbottstown",
"Troy",
"Beavertown",
],
"South Dakota": ["Yankton", "Winner"],
Tennessee: [
"Hillsboro",
"Kingsport",
"Lexington",
"Newbern",
"Brownsville",
"Lavergne",
"Memphis",
"Jonesborough",
"Dyer",
],
Texas: ["Shiner", "Plainview", "Odessa", "Rosenberg"],
Utah: ["Brigham City", "North Logan", "Tremonton"],
Virginia: ["Rockingham", "Dayton", "Orange"],
Vermont: ["Derby", "Berlin", "Middlebury", "St. Albans"],
Washington: [
"Pascoe",
"Yakima",
"Sunnyside",
"Moses Lake",
"Spokane",
"Pomeroy",
"Burlington",
"Lynden",
"Pasco",
"Quincy",
],
Wisconsin: [
"Campbellsport",
"Coleman",
"Somerset",
"Chili",
"Cross Plains",
"Reedsburg",
"Burlington",
"Spring Valley",
"Sparta",
"Ridgeland",
"Kaukauna",
"Somerset",
"Dale",
"Fond Du Lac",
"New Franken",
"Seymour",
"Stevens Point",
"Wausau",
"Markesan",
],
Wyoming: ["Riverton", "Gillette", "Powell", "Worland", "Gillette"],
};
const cityDropdown = document.getElementById("cityDropdown");
const selectedCitySpan = document.getElementById("selectedCitySpan");
cityDropdown.innerHTML = ""; // Limpiar opciones anteriores
const cities = citiesByState[state];
if (cities !== undefined) {
const sortedCities = cities.slice().sort(); // Copia y ordena alfabéticamente
const allCitiesOption = document.createElement("a");
allCitiesOption.textContent = "All cities";
allCitiesOption.onclick = () => handleCitySelection("All cities");
cityDropdown.appendChild(allCitiesOption);
sortedCities.forEach((city) => {
if (city) {
const cityOption = document.createElement("a");
cityOption.textContent = city;
cityOption.onclick = () => handleCitySelection(city);
cityDropdown.appendChild(cityOption);
}
});
} else if (
cities === undefined &&
state !== "All States" &&
state !== "All provinces/territories"
) {
const defaultOption = document.createElement("a");
defaultOption.textContent = "No cities available";
defaultOption.style.pointerEvents = "none";
cityDropdown.appendChild(defaultOption);
Swal.fire({
title: "No dealers found",
text: "No dealers found for the selected state",
icon: "info",
confirmButtonText: "Close",
animation: true,
width: "20%",
position: "center",
customClass: {
title: "swal2-title-custom",
popup: "swal2-popup-custom",
confirmButton: "swal2-confirm-button-custom",
},
});
}
}
function handleCitySelection(city) {
const selectedCitySpan = document.getElementById("selectedCitySpan");
selectedCity = city;
selectedCitySpan.textContent = city;
}
tippy("#findNearestButton", {
content:
"Discover dealers closest to you within a 50-mile radius based on your current location",
theme: "light-border",
animation: "shift-away-subtle",
popperOptions: {
modifiers: [
{
name: "applyStyles",
options: {
styles: {
fontFamily: "Montserrat",
fontSize: "14px",
color: "rgba(84, 85, 87, 1)",
},
},
},
],
},
});
document
.getElementById("findNearestButton")
.addEventListener("touchstart", function () {
findNearestDealers(userLocation);
});
function updateButton() {
const button = document.getElementById("allStatesButton");
const selectedCountry = document.getElementById(
"selectedCountrySpan"
).textContent;
console.log("pais seleccionado", selectedCountry);
if (selectedCountry === "USA") {
button.textContent = "All States";
button.className = "allStatesButton";
button.onclick = function () {
usaStates();
};
} else if (selectedCountry === "Canada") {
button.textContent = "All Provinces/Territories";
button.className = "allProvincesTerritoriesButton";
button.onclick = function () {
canadaProvincesAndTerritories();
};
}
}
function usaStates() {
showMap("All States");
selectState("All States");
loadStates("USA");
loadTableCSV();
updateTableByState();
}
function canadaProvincesAndTerritories() {
showMap("All provinces/territories");
selectState("All provinces/territories");
loadStates("Canada");
loadTableCSV();
updateTableByState();
}