PageSourceSearch

https://zavodteplic.ru/static/js/initMap.js?v=1748439076

js zavodteplic.ru collected 2026-10-04 09:04:54 UTC 8,289 bytes, 187 lines download raw bytes

1/** @namespace ymaps */
2/** @namespace item.GeoObjectCollection */
3/** @namespace item.Placemark */
4/** @namespace item.Button */
5
6
7let YaMapsShown = false;
8const mapContainer = 'contacts__ymaps'
9
10
11window.addEventListener('scroll', function () {
12  if (!YaMapsShown && document.getElementById(mapContainer)) {
13    if (onScreen(document.getElementById(mapContainer))) {
14      YaMapsShown = true
15      showYaMaps()
16    }
17  }
18});
19
20$(window).on('load', function () {
21  if (!YaMapsShown && document.getElementById(mapContainer)) {
22    if (onScreen(document.getElementById(mapContainer))) {
23      YaMapsShown = true
24      showYaMaps()
25    }
26  }
27});
28
29function showYaMaps() {
30  let script = document.createElement("script");
31  script.type = "text/javascript";
32  script.src = '//api-maps.yandex.ru/2.1/?apikey=' + mapKey + '&lang=ru_RU';
33  script.addEventListener('load', function () {
34    try {
35      if (document.getElementById(mapContainer)) {
36        ymaps.ready(initMap);
37      }
38    } catch (e) {
39      console.error('Yandex.Map not download!');
40    }
41  }, false)
42  document.body.appendChild(script);
43}
44
45/** инициализация карты Яндекса */
46function initMap() {
47  // Ищем координаты текущего города
48  let cityCoords = $('.contacts').first().attr('data-coords').split(',');
49  // Инициализация яндекс карты
50  let contactMap = new ymaps.Map(mapContainer, {
51    controls: ['fullscreenControl'],
52    center: cityCoords,
53    zoom: 12
54  });
55  contactMap.behaviors.disable('scrollZoom');
56  contactMap.controls.add(new ymaps.control.ZoomControl({
57    options: {
58      position: {
59        right: 10,
60        top: document.querySelector('#contacts__ymaps').offsetHeight / 2 - 206
61      }
62    }
63  }));
64
65  // Открываем заглушку на телефоне и планшете
66  if ($(window).width() < '1024') {
67    let wrapper = $('#contacts__windows');
68    wrapper.removeClass('hidden');
69    wrapper.on('click', function () {
70      wrapper.addClass('hidden');
71    });
72  }
73
74  // Создаем список координат
75  let coordsBranch = [];
76  $('.contacts__item[data-coords]').each(function () {
77    let coords = $(this).attr('data-coords').split(";").filter(coord => coord);
78    let address = $(this).attr('data-address').split(";").filter(address => address);
79    let type = $(this).attr('data-type'); // Получаем тип для каждой метки
80
81    coords.forEach((coord, index) => {
82      if (coordsBranch.indexOf(coords) === -1 && coord !== '') coordsBranch.push({
83          coords: coord,
84          hint: address[index],
85          type: type
86        });
87    })
88  });
89
90  // Если присутствуют филиалы настраиваем карту
91  if (coordsBranch.length) {
92
93    // Создаем коллекцию меток текущих филиалов
94    let currentBranches = new ymaps.GeoObjectCollection({}, {
95      preset: 'islands#blueIcon',
96      iconColor: '#dd514c',
97      // hintContent: "Хинт метки"
98    });
99
100    // Заполняем коллекцию
101    coordsBranch.forEach(function (item) {
102      const isExhibit = item.type === 'выставочные образцы';
103
104      currentBranches.add(new ymaps.Placemark(
105        item.coords.split(','),
106        {
107          hintContent: '<div class="contact-hint">' +
108            (item.type ? '<strong>' + item.type.charAt(0).toUpperCase() + item.type.slice(1) + '</strong><br>' : '') +
109            item.hint +
110            '</div>',
111          balloonContentBody:
112            '<b>' + (item.type ? item.type.charAt(0).toUpperCase() + item.type.slice(1) : '') + '</b>' +
113            (item.type ? ' <br>' : '') +
114            '<b>Адрес:</b> <br>' + item.hint
115        },
116        {
117          preset: isExhibit ? 'islands#blueIcon' : 'islands#redIcon'
118        }
119      ));
120    });
121
122    // Добавляем метки на карту
123    contactMap.geoObjects.add(currentBranches);
124
125
126    // function getCenter() {
127    //   // Центрирование карты
128    //   if (currentBranches.getLength() > 1)
129    //     contactMap.setBounds(currentBranches.getBounds(), {checkZoomRange: true, zoomMargin: 100});
130    //   else
131    //     contactMap.setCenter(currentBranches.getBounds()[0], 17);
132    // }
133
134
135    function getCenter() {
136      // Массив с координатами для Москвы (костыль, так как пока не придумал, как это оптимизировать)
137      let specificCoords = [
138        "55.703574126952425,37.3561726111", // Координаты точки в Москве (костыль)
139        "55.709094,37.803506"               // Еще одна точка в Москве (костыль)
140      ];
141
142      // Проверяем, есть ли в coordsBranch хотя бы одна координата, которая соответствует точкам из specificCoords
143      let foundCoords = coordsBranch.some(item => specificCoords.includes(item.coords));
144
145      // Определяем, является ли текущее устройство десктопом (ширина экрана больше 640px)
146      // Это важно, так как на мобильных устройствах мы не хотим изменять центр карты или зум
147      let isDesktop = window.innerWidth > 640;
148
149      // Если на карте больше одной точки (т.е. есть несколько объектов), применяем метод для работы с границами карты
150      if (currentBranches.getLength() > 1) {
151        // Устанавливаем границы карты, учитывая все объекты, и добавляем отступы для улучшенного отображения
152        contactMap.setBounds(currentBranches.getBounds(), {checkZoomRange: true, zoomMargin: 100});
153
154        // Если найдены нужные координаты и устройство десктопное, смещаем центр карты
155        if (foundCoords && isDesktop) {
156          // Используем setTimeout, чтобы дать карте время на обновление перед применением изменений
157          setTimeout(() => {
158            // Получаем текущие координаты центра карты
159            let center = contactMap.getCenter();
160            // Смещаем центр карты вниз (по оси Y) на 0.2 и уменьшаем зум до 11, чтобы увеличить область отображения
161            contactMap.setCenter([center[0], center[1] - 0.2], 10); // Смещение центра и зум для Москвы (костыль)
162          }, 500); // Задержка для асинхронного выполнения
163        }
164      } else {
165        // Если на карте только одна точка (один объект), устанавливаем центр карты на эту точку с зумом 17
166        contactMap.setCenter(currentBranches.getBounds()[0], 17);
167
168        // Если найдены нужные координаты и это десктоп, применяем изменения центра карты
169        if (foundCoords && isDesktop) {
170          // Устанавливаем задержку, чтобы карта успела отобразиться
171          setTimeout(() => {
172            // Получаем текущий центр карты
173            let center = contactMap.getCenter();
174            // Смещаем центр карты немного вверх (по оси Y) на 0.02 и увеличиваем зум до 15
175            // Это нужно для того, чтобы карта показывала более детально точку, если она в нашем списке
176            contactMap.setCenter([center[0], center[1] + 0.02], 15); // Смещение центра и зум для Москвы (костыль)
177          }, 500); // Задержка для асинхронного выполнения
178        }
179      }
180    }
181
182
183    // Центрируем карту
184    getCenter();
185
186  }
187}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.