test/apps/main/templates/main_index.html
2025-02-11 10:27:45 +07:00

944 lines
39 KiB
HTML
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.

{% extends "default.html" %}
{% load static %}
{% load mysettings %}
{% block header_link %}
<link rel="stylesheet"
href="{% static 'lte/plugins/icheck-bootstrap/icheck-bootstrap.min.css' %}?ver={% settings_value 'APP_VER' %}">
<link rel="stylesheet" href="{% static 'js/ol/theme/default/style.css' %}?ver={% settings_value 'APP_VER' %}">
<link rel="stylesheet" href="{% static 'js/ol/theme/default/ol.css' %}?ver={% settings_value 'APP_VER' %}">
<style>
/* Позиционирование контрола в правом нижнем углу */
.layer-switcher-bottom-right {
position: absolute;
bottom: 10px; /* Отступ от нижней границы */
right: 10px; /* Отступ от правой границы */
z-index: 1000;
}
.ol-layer-list {
list-style: none;
}
#time-slider {
width: 200px;
height: 5px;
background: #ccc;
outline: none;
border-radius: 5px;
-webkit-appearance: none;
appearance: none;
}
#time-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 15px;
height: 15px;
background: #007bff;
border-radius: 50%;
cursor: pointer;
}
#time-slider::-moz-range-thumb {
width: 15px;
height: 15px;
background: #007bff;
border-radius: 50%;
cursor: pointer;
}
.bg-orange {
background-color: #FF5F15;
color: #fff !important;
}
.bg-warning {
color: #fff !important;
}
</style>
{% endblock header_link %}
{% block content %}
<section class="content text-sm">
{% csrf_token %}
<div class="card h-100 mt-1">
<div class="card-body table-responsive p-0"
style="height: 75vh; padding-left: 0;">
<div id="map">
<button type="button" id="toStart" class="btn"
style="position: absolute; top: .5em; left: .5em; z-index: 999; background-color: rgba(255,255,255, 0.5); border: 1px solid #e2c4b0">
Вернуться на разрез
</button>
<div id="popup"></div>
<div id="slider-container"
style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); z-index: 1000; background: rgba(255, 255, 255, 0.8); padding: 10px; border-radius: 5px;">
<input type="range" id="time-slider" min="0" max="100" value="100" step="1"
style="width: 800px;">
<p id="slider-date" style="margin: 5px 0; font-size: 12px;">Текущая дата: ...</p>
</div>
{% if show_speed_excess or show_drivers_fatigue or show_seismic_activity %}
<div id="coefficients"
style="position: absolute; top: .5em; right:.5em; z-index: 1000; background: rgba(255, 255, 255, 0.8); padding: 10px; border-radius: 5px;">
<div class="h-100 w-100 d-flex divider-vertical" style="gap: 1em">
{% if show_speed_excess %}
<div class="text-center d-flex align-items-center"
style="gap: 1em; padding-right: 5px;">
<span>Превышения скорости</span>
<span class="float-right badge" style="font-size: 1em" id="SpeedExcess"></span>
</div>
{% endif %}
{% if show_drivers_fatigue %}
<div class="text-center d-flex align-items-center"
style="gap: 1em; padding-right: 5px;">
<span>Усталость водителей</span>
<span class="float-right badge" style="font-size: 1em"
id="DriversFatigue"></span>
</div>
{% endif %}
{% if show_seismic_activity %}
<div class="text-center d-flex align-items-center"
style="gap: 1em; padding-right: 5px;">
<span>Сейсмическая активность</span>
<span class="float-right badge" style="font-size: 1em"
id="SeismicActivity"></span>
</div>
{% endif %}
</div>
</div>
{% endif %}
</div>
</div>
</div>
</section>
{% endblock %}
{% block script_footer %}
<script src="{% static 'js/ol/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<script>
let OSM = {};
let map, popup = {}
// ГТО
let GTOSource = {}
let GTOLayer = {}
let GTOMarkers = {}
// Местоположение
let VlocationLayer = {}
let VlocationSource = {}
let VlocationMarkers = {}
// Сейсмика
let SPLayer = {}
let SPSource = {}
let SPMarkers = {}
let mineBorderLayer = {}
let scanSource = {}
let scanLayer = {}
let GTOZonePolygonsLayer = {}
let centerLat = '{{lon}}'
let centerLon = '{{lat}}'
const seismDays = parseInt("{{ seism_days }}");
const seismDaysInit = parseInt("{{ seism_days_init }}")
const slider = document.getElementById('time-slider');
const sliderDate = document.getElementById('slider-date');
if (!slider) {
console.error('Слайдер не найден!');
}
// Функция для форматирования даты и времени в российский формат
function formatDateToRussian(date) {
const day = String(date.getDate()).padStart(2, '0'); // День (с ведущим нулем)
const month = String(date.getMonth() + 1).padStart(2, '0'); // Месяц (с ведущим нулем, +1 так как месяцы начинаются с 0)
const year = date.getFullYear(); // Год
const hours = String(date.getHours()).padStart(2, '0'); // Часы
const minutes = String(date.getMinutes()).padStart(2, '0'); // Минуты
const seconds = String(date.getSeconds()).padStart(2, '0'); // Секунды
return `${day}.${month}.${year} ${hours}:${minutes}:${seconds}`;
}
// Инициализация слайдера
function initTimeSlider() {
const dayMilliseconds = 24 * 60 * 60 * 1000;
slider.min = 0;
slider.max = 100;
const startDate = new Date();
startDate.setDate(startDate.getDate() - seismDays);
const endDate = new Date();
const initialDate = new Date();
initialDate.setDate(initialDate.getDate() - seismDaysInit)
slider.value = calculateSliderValueFromStartDate(initialDate, startDate, endDate);
// Форматирование даты в российский формат
const formattedDate = formatDateToRussian(initialDate);
// Обновление текста с датой
sliderDate.textContent = `Землетрясения с: ${formattedDate}`;
// Отправка GET-запроса на сервер
fetchEarthquakes(initialDate);
// Обработчик изменения слайдера
slider.addEventListener('input', (event) => {
const sliderValue = parseInt(event.target.value);
// Вычисление даты на основе значения слайдера
const currentDate = calculateDateFromSlider(sliderValue, startDate, endDate);
// Форматирование даты в российский формат
const formattedDate = formatDateToRussian(currentDate);
// Обновление текста с датой
sliderDate.textContent = `Землетрясение с: ${formattedDate}`;
// Отправка GET-запроса на сервер
fetchEarthquakes(currentDate);
});
}
// Функция для вычисления даты на основе значения слайдера
function calculateDateFromSlider(value, startDate, endDate) {
const totalDays = (endDate - startDate) / (1000 * 60 * 60 * 24); // Общее количество дней
const selectedDay = Math.floor((value / 100) * totalDays); // Выбранное количество дней
return new Date(startDate.getTime() + selectedDay * 24 * 60 * 60 * 1000);
}
// Функция для вычисления значения слайдера на основе начальной даты
function calculateSliderValueFromStartDate(date, startDate, endDate) {
const totalDays = (endDate - startDate) / (1000 * 60 * 60 * 24); // Общее количество дней
const daysDifference = (date - startDate) / (1000 * 60 * 60 * 24); // Разница в днях
return Math.floor((daysDifference / totalDays) * 100); // Значение слайдера
}
// Функция для отправки GET-запроса на сервер
function fetchEarthquakes(date) {
const formattedDate = date.toISOString().split('T')[0]; // Формат YYYY-MM-DD
fetch(`/seismicproc/earthquakes/?date=${formattedDate}`)
.then(response => response.json())
.then(data => {
updateSPMarkers(data);
})
.catch(error => console.error('Ошибка при загрузке данных:', error));
}
// Функция для обновления маркеров на карте
function updateSPMarkers(filteredEarthquakes) {
if (!(SPSource instanceof ol.source.Vector)) {
console.error('SPSource не является экземпляром ol.source.Vector');
return;
}
// Очистка текущих маркеров
SPSource.clear();
// Добавление новых маркеров
filteredEarthquakes.forEach(earthquake => {
addSPMarker(earthquake);
});
}
const getGTOMarkerText = function (feature) {
const statemum = feature.get('garagenum')
if (statemum) {
return statemum;
}
return feature.get('name')
};
const createGTOStateNumTextStyle = function (feature, resolution) {
const font = 'bold' + ' ' + '12px' + '/' + '1' + ' ' + 'Arial';
return new ol.style.Text({
textAlign: 'center',
textBaseline: 'middle',
font: font,
text: getGTOMarkerText(feature, resolution),
fill: new ol.style.Fill({color: '#000'}),
offsetX: 0,
offsetY: -25,
placement: 'point',
maxAngle: '0.7853981633974483',
overflow: 'false',
rotation: parseFloat('0'),
backgroundFill: new ol.style.Fill({color: '#fff'}),
backgroundStroke: new ol.style.Stroke({color: '#000', width: 1}),
padding: [3, 3, 3, 3],
});
};
const createGTOZoneNameTextStyle = function (feature, resolution) {
const font = 'bold' + ' ' + '9px' + '/' + '1' + ' ' + 'Arial';
return new ol.style.Text({
textAlign: 'center',
textBaseline: 'middle',
font: font,
text: getGTOMarkerText(feature, resolution),
fill: new ol.style.Fill({color: '#000'}),
offsetX: 0,
offsetY: -25,
placement: 'point',
maxAngle: '0.7853981633974483',
overflow: 'false',
rotation: parseFloat('0'),
padding: [3, 3, 3, 3],
});
};
function GTOStyleFunction(feature, resolution) {
return new ol.style.Style({
image: new ol.style.Icon({
src: feature.get('icon') ? feature.get('icon') : "/static/img/belaz.png",
width: 30,
height: 20
}),
text: createGTOStateNumTextStyle(feature, resolution)
})
}
function createHatchPattern() {
// Создаем элемент canvas для шаблона штриховки
const canvas = document.createElement('canvas');
canvas.width = 10; // Ширина шаблона
canvas.height = 10; // Высота шаблона
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'rgba(125, 105, 49, 0.1)'; // Цвет штриховки
ctx.lineWidth = 2;
// Рисуем диагональные линии для штриховки
ctx.beginPath();
ctx.moveTo(0, 10);
ctx.lineTo(10, 0);
ctx.stroke();
// Создаем паттерн из канваса
return ctx.createPattern(canvas, 'repeat');
}
function VlocationStyleFunction(feature, resolution) {
return new ol.style.Style({
image: new ol.style.Icon({
src: '/static/img/worker.png',
width: 25,
height: 30
})
})
}
function SPStyleFunction(feature, resolution) {
return new ol.style.Style({
image: new ol.style.Icon({
src: '/static/img/earthquake_yellow.png',
width: 25,
height: 30
})
})
}
function polygonStyleFunction(feature, resolution) {
return new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgb(0,117,217)',
width: 2,
}),
fill: new ol.style.Fill({
color: createHatchPattern(),
}),
});
}
function polygonBrownStyleFunction(feature, resolution) {
return new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgb(199,136,10)',
width: 2,
}),
fill: new ol.style.Fill({
color: 'rgba(199,136,10, 0.6)',
}),
text: createGTOZoneNameTextStyle(feature, resolution)
});
}
function moveMarker(marker, newCoordinates) {
const duration = 2000; // Длительность анимации в миллисекундах
const startCoordinates = marker.getGeometry().getCoordinates();
// Начало анимации
const startTime = performance.now();
function animate(currentTime) {
// Вычисление прошедшего времени
const elapsed = currentTime - startTime;
// Вычисление доли анимации (от 0 до 1)
const fraction = Math.min(elapsed / duration, 1);
// Интерполяция координат
const interpolatedCoordinates = [
startCoordinates[0] + fraction * (newCoordinates[0] - startCoordinates[0]),
startCoordinates[1] + fraction * (newCoordinates[1] - startCoordinates[1]),
];
// Устанавливаем новые координаты для маркера
marker.getGeometry().setCoordinates(interpolatedCoordinates);
// Продолжаем анимацию, если она еще не завершена
if (fraction < 1) {
requestAnimationFrame(animate);
}
}
// Запуск анимации
requestAnimationFrame(animate);
}
class LayerSwitcherControl extends ol.control.Control {
/**
* @param {Object} [opt_options] Control options.
*/
constructor(opt_options) {
const options = opt_options || {};
// Создание кнопки для переключателя слоёв
const button = document.createElement('button');
button.innerHTML = `<i class="fa fa-layer-group"></i>`; // Иконка для кнопки
// Создание контейнера для контрола
const element = document.createElement('div');
element.className = 'layer-switcher ol-unselectable ol-control layer-switcher-bottom-right'; // Добавляем класс для позиционирования
element.appendChild(button);
super({
element: element,
target: options.target,
});
// Слушатель нажатия на кнопку
button.addEventListener('click', this.toggleLayerList.bind(this), false);
// Список слоёв (скрытый по умолчанию)
this.layerList = document.createElement('ul');
this.layerList.className = 'ol-layer-list';
this.layerList.style.display = 'none';
element.appendChild(this.layerList);
// Подключаем событие для обновления списка слоёв после инициализации карты
this.onMapLoaded();
}
/**
* Переключение видимости списка слоёв
*/
toggleLayerList() {
if (this.layerList.style.display === 'block') {
this.layerList.style.display = 'none';
} else {
this.layerList.style.display = 'block';
}
}
/**
* Обновление списка слоёв в контроле
*/
updateLayerList() {
const map = this.getMap();
if (!map) {
return;
}
const layers = map.getLayers().getArray();
// Очищаем старый список
this.layerList.innerHTML = '';
layers.forEach((layer) => {
const layerItem = document.createElement('li');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = layer.getVisible(); // Задаем состояние видимости слоя
checkbox.addEventListener('click', () => {
layer.setVisible(checkbox.checked); // Изменение видимости слоя
});
const label = document.createElement('label');
label.innerHTML = layer.get('name') || 'Unnamed Layer'; // Отображение названия слоя
layerItem.appendChild(checkbox);
layerItem.appendChild(label);
this.layerList.appendChild(layerItem);
});
}
/**
* Ожидаем, когда карта будет инициализирована, и обновим список слоёв
*/
onMapLoaded() {
const map = this.getMap();
if (map) {
this.updateLayerList();
// Подписываемся на изменения слоёв
map.on('change:layers', () => {
this.updateLayerList();
});
} else {
// В случае, если карта еще не инициализирована, используем setTimeout
setTimeout(this.onMapLoaded.bind(this), 100);
}
}
}
function initializeMap() {
OSM = new ol.layer.Tile({
source: new ol.source.OSM(), // Open street Map
})
OSM.set('name', 'OpenStreet Map')
// Источник данных для GTO
GTOSource = new ol.source.Vector();
// Слой для отображения GTO
GTOLayer = new ol.layer.Vector({
source: GTOSource,
style: GTOStyleFunction
});
GTOLayer.set('name', 'Горнотранспортное оборудование')
// Источник данных для Vlocation
VlocationSource = new ol.source.Vector();
// Слой для Vlocation
VlocationLayer = new ol.layer.Vector({
source: VlocationSource,
style: VlocationStyleFunction
})
VlocationLayer.set('name', 'Местоположение сотрудников')
SPSource = new ol.source.Vector();
SPLayer = new ol.layer.Vector({
source: SPSource,
style: SPStyleFunction
});
SPLayer.set('name', 'Сейсмические процессы')
initTimeSlider()
mineBorderLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: '/{{ prgr }}',
format: new ol.format.KML({extractStyles: false}),
}),
style: polygonStyleFunction,
});
mineBorderLayer.set('name', 'Границы ПРГР')
scanLayer = new ol.layer.Tile({
source: new ol.source.XYZ({
url: '/media/map/orth/tiles/{z}/{x}/{y}.png?ver={% settings_value 'APP_VER' %}',
}),
extent: ol.proj.transformExtent(
[
parseFloat('{{ orth_minLon }}'),
parseFloat('{{ orth_minLat }}'),
parseFloat('{{ orth_maxLon }}'),
parseFloat('{{ orth_maxLat }}')
],
'EPSG:4326', // Исходная проекция
'EPSG:3857' // Целевая проекция
)
});
scanLayer.set('name', 'Ортофотоплан')
GTOZonePolygonsLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: '/gto/polygons/',
format: new ol.format.GeoJSON(),
}),
style: polygonBrownStyleFunction,
});
GTOZonePolygonsLayer.set('name', 'Зоны')
const layers = [
OSM,
GTOZonePolygonsLayer,
mineBorderLayer,
SPLayer,
VlocationLayer,
GTOLayer,
]
const scanLayerExists = Boolean(parseInt('{{ scan_layer_enable }}'))
if (scanLayerExists) {
layers.splice(1, 0, scanLayer)
}
// Создание карты
map = new ol.Map({
target: 'map', // ID элемента, куда встроится карта
controls: [
new LayerSwitcherControl(),
new ol.control.ScaleLine(),
new ol.control.ZoomSlider()
],
layers: layers,
view: new ol.View({
center: ol.proj.fromLonLat([centerLat, centerLon]), // Центр карты
zoom: 12,
}),
});
const element = document.getElementById('popup')
// Всплывающее окно
popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
{#autoPan: true,#}
});
map.addOverlay(popup);
let popover;
function disposePopover() {
if (popover) {
popover.dispose();
popover = undefined;
}
}
// Обработка кликов по маркерам
map.on('click', function (evt) {
// Получение feature по клику
const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
// Удаление существующего popover
disposePopover();
if (!feature) {
return; // Если feature не найден, ничего не делаем
}
// Получение координат клика
const coordinates = evt.coordinate;
// Получение контейнера элемента popup
const element = document.getElementById('popup'); // Убедитесь, что этот элемент существует в DOM
// Установка позиции popup на карте
popup.setPosition(coordinates);
function createPopover(feature) {
const res = document.createElement('div')
const properties = feature.getProperties()
for (let property in properties) {
switch (property) {
case 'name': {
let div = document.createElement('div')
let span = document.createElement('span')
let strong = document.createElement('strong')
strong.textContent = "Имя: "
div.appendChild(strong)
span.textContent = feature.get('name')
div.appendChild(span)
res.appendChild(div)
break
}
case 'lat': {
let div = document.createElement('div')
let span = document.createElement('span')
let strong = document.createElement('strong')
strong.textContent = "Координаты: "
div.appendChild(strong)
span.textContent = feature.get('lat') + ' ' + feature.get('lon')
div.appendChild(span)
res.appendChild(div)
break
}
case 'time': {
let div = document.createElement('div')
let span = document.createElement('span')
let strong = document.createElement('strong')
strong.textContent = "Время координаты: "
div.appendChild(strong)
span.textContent = feature.get('time')
div.appendChild(span)
res.appendChild(div)
break
}
case 'statenum': {
let div = document.createElement('div')
let span = document.createElement('span')
let strong = document.createElement('strong')
strong.textContent = "Госномер: "
div.appendChild(strong)
span.textContent = feature.get('statenum')
div.appendChild(span)
res.appendChild(div)
break
}
case 'garagenum': {
let div = document.createElement('div')
let span = document.createElement('span')
let strong = document.createElement('strong')
strong.textContent = "Гаражный номер: "
div.appendChild(strong)
span.textContent = feature.get('garagenum')
div.appendChild(span)
res.appendChild(div)
break
}
case "depth": {
let div = document.createElement('div')
let span = document.createElement('span')
let strong = document.createElement('strong')
strong.textContent = "Глубина: "
div.appendChild(strong)
span.textContent = feature.get('depth') + " км."
div.appendChild(span)
res.appendChild(div)
break
}
case "magnitude": {
let div = document.createElement('div')
let span = document.createElement('span')
let strong = document.createElement('strong')
strong.textContent = "Магнитуда: "
div.appendChild(strong)
span.textContent = feature.get('magnitude')
div.appendChild(span)
res.appendChild(div)
break
}
case "region": {
let div = document.createElement('div')
let span = document.createElement('span')
let strong = document.createElement('strong')
strong.textContent = "Регион: "
div.appendChild(strong)
span.textContent = feature.get('region')
div.appendChild(span)
res.appendChild(div)
break
}
case "source": {
let div = document.createElement('div')
let span = document.createElement('span')
let strong = document.createElement('strong')
strong.textContent = "Источник: "
div.appendChild(strong)
span.textContent = feature.get('source')
div.appendChild(span)
res.appendChild(div)
break
}
}
}
return res
}
// Создание нового popover
popover = new bootstrap.Popover(element, {
placement: 'top', // Расположение popover
html: true, // Поддержка HTML-содержимого
content: createPopover(feature),
});
// Отображение popover
popover.show();
});
map.on('movestart', disposePopover);
map.on("pointermove", function (evt) {
var hit = this.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
return true;
});
if (hit) {
this.getTargetElement().style.cursor = 'pointer';
} else {
this.getTargetElement().style.cursor = '';
}
});
// Загрузка маркеров
updateMarkers();
setInterval(updateMarkers, 5000)
}
function addGTOMarker(equipment) {
const point = new ol.geom.Point(ol.proj.fromLonLat([equipment.lon, equipment.lat]));
const feature = new ol.Feature(point);
feature.setProperties({
name: equipment.name,
time: equipment.time,
lat: equipment.lat,
lon: equipment.lon,
statenum: equipment.statenum,
garagenum: equipment.garagenum,
model: equipment.model,
icon: equipment.icon
});
GTOSource.addFeature(feature);
GTOMarkers[equipment.id] = feature;
}
function addVlocationMarker(worker) {
const point = new ol.geom.Point(ol.proj.fromLonLat([worker.lon, worker.lat]));
const feature = new ol.Feature(point);
feature.setProperties({
name: worker.name,
lat: worker.lat,
lon: worker.lon,
time: worker.time,
})
VlocationSource.addFeature(feature)
VlocationMarkers[worker.id] = feature
}
function addSPMarker(earthquake) {
const point = new ol.geom.Point(ol.proj.fromLonLat([earthquake.lon, earthquake.lat]));
const feature = new ol.Feature(point);
feature.setProperties({
depth: earthquake.depth,
lat: earthquake.lat,
lon: earthquake.lon,
magnitude: earthquake.magnitude,
region: earthquake.region,
source: earthquake.source,
time: earthquake.time
})
SPSource.addFeature(feature)
SPMarkers[earthquake.id] = feature
}
function updateMarkers() {
fetch('/gto/update_object/', {
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
mode: 'same-origin',
})
.then(response => response.json())
.then(data => {
data.forEach(equipment => {
if (GTOMarkers[equipment.id]) {
const marker = GTOMarkers[equipment.id];
const currentCoordinates = marker.getGeometry().getCoordinates();
const newCoordinates = ol.proj.fromLonLat([equipment.lon, equipment.lat]);
// Проверяем, изменились ли координаты
if (currentCoordinates[0] !== newCoordinates[0] || currentCoordinates[1] !== newCoordinates[1]) {
moveMarker(marker, newCoordinates); // Плавное перемещение
}
} else {
// Создаем новый маркер, если его ещё нет
addGTOMarker(equipment);
}
});
});
fetch('/wklocation/update_object/')
.then(response => response.json())
.then(data => {
data.forEach(worker => {
if (VlocationMarkers[worker.id]) {
const marker = VlocationMarkers[worker.id]
const currentCoordinates = marker.getGeometry().getCoordinates();
const newCoordinates = ol.proj.fromLonLat([worker.lon, worker.lat]);
if (currentCoordinates[0] !== newCoordinates[0] || currentCoordinates[1] !== newCoordinates[1]) {
moveMarker(marker, newCoordinates); // Плавное перемещение
}
} else {
addVlocationMarker(worker)
}
})
})
fetch("/main/coefficients/")
.then(response => response.json())
.then(data => {
for (const item in data) {
const elem = document.querySelector(`#${item}`);
if (elem) { // Проверяем, что элемент существует
elem.textContent = data[item] + "%";
// Удаляем все возможные классы перед добавлением нового
elem.classList.remove("bg-success", "bg-warning", "bg-orange", "bg-danger");
// Добавляем нужный класс в зависимости от значения
if (75 <= data[item] && data[item] <= 100) {
elem.classList.add("bg-success");
} else if (50 <= data[item] && data[item] < 75) {
elem.classList.add("bg-warning");
} else if (25 <= data[item] && data[item] < 50) {
elem.classList.add("bg-orange");
} else if (data[item] < 25) {
elem.classList.add("bg-danger");
}
}
}
})
.catch(error => {
console.error("Ошибка при получении данных:", error);
});
{#fetchEarthquakes()#}
}
let toStart = document.querySelector('#toStart')
toStart.addEventListener('click', ev => {
map.setView(new ol.View({
center: ol.proj.fromLonLat([centerLat, centerLon]), // Центр карты
zoom: 12,
}))
})
window.onload = initializeMap;
</script>
{% endblock script_footer %}