Files
hotel777/public/location.js
2026-05-02 21:51:32 +05:00

236 lines
9.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Координаты отеля
const HOTEL_COORDS = [43.139637, 40.527054];
const HOTEL_ADDRESS = "Набережная улица, 1, село Мгудзырхуа, Гудаутский район, Абхазия";
// Данные городов с расстояниями (км) и ключами для перевода
const citiesData = [
{ key: "sukhum", distance: 51 },
{ key: "ochamchyra", distance: 105 },
{ key: "tkvarcheli", distance: 165 },
{ key: "gal", distance: 145 },
{ key: "new_athos", distance: 25 },
{ key: "primorsk", distance: 20 },
{ key: "gudauta", distance: 10 }
];
// Цвета для карточек городов (циклически)
const cityColors = [
"#FFB3BA", "#C5E99B", "#B5E3FF", "#FFD6A5", "#D4A5FF", "#A5FFD6", "#FFA5D6"
];
let map = null;
let placemark = null;
let mapVisible = false;
let currentLang = localStorage.getItem('siteLang') || 'ru';
// Функция получения перевода названия города
function getCityTranslation(cityKey, lang) {
const transMap = {
sukhum: window.translations[lang].loc_city_sukhum,
ochamchyra: window.translations[lang].loc_city_ochamchyra,
tkvarcheli: window.translations[lang].loc_city_tkvarcheli,
gal: window.translations[lang].loc_city_gal,
new_athos: window.translations[lang].loc_city_new_athos,
primorsk: window.translations[lang].loc_city_primorsk,
gudauta: window.translations[lang].loc_city_gudauta
};
return transMap[cityKey] || cityKey;
}
// Генерация HTML для секции location (карта под картинкой, кнопка между координатами и городами)
function generateLocationHTML(lang) {
const addressLabel = window.translations[lang].loc_address_label;
const coordsLabel = window.translations[lang].loc_coords_label;
const kmLabel = window.translations[lang].loc_km;
const showMapBtnText = window.translations[lang].loc_show_map || "Показать карту";
// Создаём разноцветные карточки городов
const cardsHTML = citiesData.map((city, idx) => `
<div class="location-card" style="background-color: ${cityColors[idx % cityColors.length]}">
<div class="location-icon">🚗</div>
<div class="location-title">${getCityTranslation(city.key, lang)}</div>
<div class="location-distance">${city.distance} ${kmLabel}</div>
</div>
`).join('');
return `
<h2 class="section-title animate" data-i18n="loc_title">${window.translations[lang].loc_title}</h2>
<div class="about-grid">
<!-- Левая колонка: адрес, координаты, кнопка, города -->
<div class="about-text animate delay-1">
<p style="font-size:1.1rem; margin-bottom:1.5rem;"><strong>${addressLabel}</strong></p>
<div style="background:var(--input-bg); padding:2rem; border-radius:16px; margin-bottom:1.5rem;">
<span style="font-size:1.1rem;">${HOTEL_ADDRESS}</span>
</div>
<div style="background:var(--input-bg); padding:2rem; border-radius:16px; margin-bottom:1.5rem;">
<span style="font-size:1.1rem;"><strong>${coordsLabel}</strong> ${HOTEL_COORDS[0]}, ${HOTEL_COORDS[1]}</span>
</div>
<!-- Кнопка показа карты
<button id="showMapBtn" class="btn show-map-btn" style="margin-bottom: 1.5rem; width: 100%;">${showMapBtnText}</button>
-->
<div class="location-cards">
${cardsHTML}
</div>
</div>
<!-- Правая колонка: картинка и под ней карта (скрыта по умолчанию) -->
<div class="about-image-wrapper animate delay-2">
<img src="img/znak.webp" alt="Указатель Hotel 777" class="about-img signpost-img location-img-animate" id="signpostImg" loading="lazy">
<div id="yandexMap" class="map-container" style="display: none;"></div>
</div>
</div>
`;
}
// Инициализация карты (вызывается только при первом нажатии кнопки)
function initMapOnce() {
if (!window.ymaps) {
console.warn("Яндекс.Карты не загружены");
return;
}
const mapContainer = document.getElementById('yandexMap');
if (!mapContainer) return;
if (!map) {
window.ymaps.ready(() => {
map = new window.ymaps.Map('yandexMap', {
center: HOTEL_COORDS,
zoom: 14,
controls: ['zoomControl', 'fullscreenControl']
});
placemark = new window.ymaps.Placemark(HOTEL_COORDS, {
hintContent: HOTEL_ADDRESS,
balloonContent: HOTEL_ADDRESS
}, {
preset: 'islands#redDotIcon'
});
map.geoObjects.add(placemark);
});
}
}
// Показать карту (по кнопке)
function showMap() {
const mapContainer = document.getElementById('yandexMap');
if (!mapContainer) return;
if (!map) {
initMapOnce();
// Небольшая задержка, чтобы карта успела создаться, затем показываем контейнер
setTimeout(() => {
mapContainer.style.display = 'block';
if (map) {
window.ymaps.ready(() => {
map.container.fitToViewport();
});
}
}, 300);
} else {
mapContainer.style.display = 'block';
window.ymaps.ready(() => {
map.container.fitToViewport();
});
}
mapVisible = true;
}
// Обновление текстов (без пересоздания карты)
function updateLocationTexts(lang) {
const locationSection = document.getElementById('location');
if (!locationSection) return;
const title = locationSection.querySelector('.section-title');
if (title && window.translations[lang].loc_title) {
title.innerHTML = window.translations[lang].loc_title;
}
const aboutText = locationSection.querySelector('.about-text');
if (aboutText) {
const addressLabelStrong = aboutText.querySelector('p strong');
if (addressLabelStrong) addressLabelStrong.textContent = window.translations[lang].loc_address_label;
const coordsSpan = aboutText.querySelector('div:last-of-type span strong');
if (coordsSpan) coordsSpan.textContent = window.translations[lang].loc_coords_label;
// Обновляем текст кнопки
const showBtn = aboutText.querySelector('#showMapBtn');
if (showBtn && window.translations[lang].loc_show_map) {
showBtn.textContent = window.translations[lang].loc_show_map;
}
// Обновляем карточки городов
const cards = aboutText.querySelectorAll('.location-card');
cards.forEach((card, idx) => {
if (citiesData[idx]) {
const titleDiv = card.querySelector('.location-title');
if (titleDiv) titleDiv.textContent = getCityTranslation(citiesData[idx].key, lang);
const distSpan = card.querySelector('.location-distance');
if (distSpan) distSpan.textContent = `${citiesData[idx].distance} ${window.translations[lang].loc_km}`;
}
});
}
if (map && placemark) {
placemark.properties.set({
hintContent: HOTEL_ADDRESS,
balloonContent: HOTEL_ADDRESS
});
}
}
// Полная отрисовка секции location
function renderLocation(lang) {
const locationSection = document.getElementById('location');
if (!locationSection) return;
locationSection.innerHTML = generateLocationHTML(lang);
// Анимация картинки при прокрутке
const signImg = document.getElementById('signpostImg');
if (signImg) {
const imgObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('in-view');
imgObserver.unobserve(entry.target);
}
});
}, { threshold: 0.3 });
imgObserver.observe(signImg);
}
// Назначаем обработчик на кнопку показа карты
const showBtn = document.getElementById('showMapBtn');
if (showBtn) {
showBtn.addEventListener('click', showMap);
}
// Запуск анимаций для новых .animate элементов
document.querySelectorAll('.animate').forEach(el => {
if (el.style.animationPlayState !== 'running') {
el.style.animationPlayState = 'paused';
const obs = new IntersectionObserver(entries => {
entries.forEach(en => { if(en.isIntersecting) en.target.style.animationPlayState = 'running'; });
});
obs.observe(el);
}
});
}
function updateLocationLanguage(lang) {
currentLang = lang;
if (document.getElementById('location').innerHTML.trim() !== '') {
updateLocationTexts(lang);
} else {
renderLocation(lang);
}
}
window.updateLocationLanguage = updateLocationLanguage;
document.addEventListener("DOMContentLoaded", () => {
setTimeout(() => {
renderLocation(currentLang);
}, 300);
});