88 lines
3.1 KiB
JavaScript
88 lines
3.1 KiB
JavaScript
(function () {
|
|
var mapEl = document.getElementById('ya-map');
|
|
if (!mapEl) return;
|
|
|
|
var coordsAttr = mapEl.getAttribute('data-coords');
|
|
var label = mapEl.getAttribute('data-label') || '';
|
|
if (!coordsAttr) return;
|
|
|
|
var parts = coordsAttr.split(',');
|
|
if (parts.length < 2) return;
|
|
var mapCoords = [parseFloat(parts[0]), parseFloat(parts[1])];
|
|
if (isNaN(mapCoords[0]) || isNaN(mapCoords[1])) return;
|
|
|
|
var done = false;
|
|
var apiState = ''; // '' | loading | ready
|
|
var observer = null;
|
|
|
|
function createMap() {
|
|
if (done || typeof ymaps === 'undefined') return;
|
|
done = true;
|
|
ymaps.ready(function () {
|
|
var map = new ymaps.Map('ya-map', {
|
|
center: mapCoords,
|
|
zoom: 16
|
|
}, {
|
|
searchControlProvider: 'yandex#search'
|
|
});
|
|
map.geoObjects.add(new ymaps.Placemark(
|
|
mapCoords,
|
|
{ iconContent: label },
|
|
{ preset: 'islands#redStretchyIcon' }
|
|
));
|
|
});
|
|
}
|
|
|
|
// API мог загрузиться, но ymaps ещё не объявлен — до-
|
|
// ждать (редкий случай гонки onload)
|
|
function waitApi(tries) {
|
|
if (typeof ymaps !== 'undefined') { createMap(); return; }
|
|
if (tries <= 0) return;
|
|
setTimeout(function () { waitApi(tries - 1); }, 250);
|
|
}
|
|
|
|
function loadApi() {
|
|
if (apiState) return;
|
|
apiState = 'loading';
|
|
var script = document.createElement('script');
|
|
script.src = 'https://api-maps.yandex.ru/2.1/?lang=ru_RU';
|
|
script.onload = function () { apiState = 'ready'; waitApi(20); };
|
|
script.onerror = function () { apiState = ''; };
|
|
document.head.appendChild(script);
|
|
}
|
|
|
|
function activate() {
|
|
loadApi();
|
|
mapEl.removeEventListener('click', activate);
|
|
window.removeEventListener('scroll', onMaybeInView, { passive: true });
|
|
if (observer) { observer.disconnect(); observer = null; }
|
|
clearInterval(pollTimer);
|
|
}
|
|
|
|
// content-visibility:auto и подобное мешают IntersectionObserver — дублируем проверкой скролла и опросом
|
|
function inView() {
|
|
var r = mapEl.getBoundingClientRect();
|
|
var vh = window.innerHeight || document.documentElement.clientHeight;
|
|
return r.top < vh + 300 && r.bottom > -300;
|
|
}
|
|
function onMaybeInView() { if (inView()) { activate(); } }
|
|
|
|
var pollTries = 0;
|
|
var pollTimer = setInterval(function () {
|
|
if (inView() || ++pollTries >= 15) { activate(); }
|
|
}, 1000);
|
|
|
|
if ('IntersectionObserver' in window) {
|
|
observer = new IntersectionObserver(function (entries) {
|
|
for (var i = 0; i < entries.length; i++) {
|
|
if (entries[i].isIntersecting) { activate(); break; }
|
|
}
|
|
}, { rootMargin: '300px 0px' });
|
|
observer.observe(mapEl);
|
|
}
|
|
window.addEventListener('scroll', onMaybeInView, { passive: true });
|
|
if (inView()) { activate(); }
|
|
|
|
mapEl.addEventListener('click', activate);
|
|
})();
|