894 lines
42 KiB
HTML
894 lines
42 KiB
HTML
{% 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' %}">
|
||
<link rel="stylesheet" href="{% static 'js/ol/ol-ext/ol-ext.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||
<link rel="stylesheet" href="{% static 'js/ol/ol-ext/ol-layer-theme.css' %}?ver={% settings_value 'APP_VER' %}">
|
||
<link rel="stylesheet" href="{% static 'css/main_page.css' %}?ver={% settings_value 'APP_VER' %}">
|
||
{% endblock header_link %}
|
||
|
||
{% block content %}
|
||
|
||
<section class="content text-sm p-1">
|
||
{% csrf_token %}
|
||
<div class="card h-100">
|
||
<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="LayerSwitcher" style="position: absolute; bottom: .5em; right: .5em; z-index: 1000">
|
||
<div class="layers-btn-container">
|
||
<div id="layers-btn"></div>
|
||
</div>
|
||
<div id="LayerSwitcherInner" style="display: none">
|
||
</div>
|
||
</div>
|
||
<div id="slider-container"
|
||
style="position: absolute; bottom: .5em; 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="dropdown">
|
||
<div class="clickable-area d-flex align-items-center" data-toggle="dropdown"
|
||
aria-expanded="false"
|
||
style="cursor: pointer; gap: 1em; padding-right: 5px;">
|
||
<span>Превышения скорости</span>
|
||
<span class="float-right badge" style="font-size: 1em"
|
||
id="SpeedExcess"></span>
|
||
<i class="dropdown-icon fa fa-angle-down"
|
||
style="color: var(--primary);font-size: 1.2em;"></i>
|
||
</div>
|
||
<div class="dropdown-menu" id="dropdown-SpeedExcess" style="width: 734px;">
|
||
<ul id="dropdown-list-SpeedExcess"
|
||
style="list-style-type: none; margin: 0; padding: 0;"></ul>
|
||
</div>
|
||
</div>
|
||
{% endif %}
|
||
|
||
|
||
<!-- Усталость водителей -->
|
||
{% if show_drivers_fatigue %}
|
||
<div class="dropdown">
|
||
<div class="clickable-area d-flex align-items-center" data-toggle="dropdown"
|
||
aria-expanded="false"
|
||
style="cursor: pointer; gap: 1em; padding-right: 5px;">
|
||
<span>Усталость водителей</span>
|
||
<span class="float-right badge" style="font-size: 1em"
|
||
id="DriversFatigue"></span>
|
||
<i class="dropdown-icon fa fa-angle-down"
|
||
style="color: var(--primary);font-size: 1.2em;"></i>
|
||
</div>
|
||
<div class="dropdown-menu" id="dropdown-DriversFatigue" style="width: 734px;">
|
||
<ul id="dropdown-list-DriversFatigue"
|
||
style="list-style-type: none; margin: 0; padding: 0;"></ul>
|
||
</div>
|
||
</div>
|
||
{% endif %}
|
||
|
||
<!-- Сейсмическая активность -->
|
||
{% if show_seismic_activity %}
|
||
<div class="dropdown">
|
||
<div class="clickable-area d-flex align-items-center" data-toggle="dropdown"
|
||
aria-expanded="false"
|
||
style="cursor: pointer; gap: 1em; padding-right: 5px;">
|
||
<span>Сейсмическая активность</span>
|
||
<span class="float-right badge" style="font-size: 1em"
|
||
id="SeismicActivity"></span>
|
||
<i class="dropdown-icon fa fa-angle-down"
|
||
style="color: var(--primary);font-size: 1.2em;"></i>
|
||
</div>
|
||
<div class="dropdown-menu" id="dropdown-SeismicActivity" style="width: 734px;">
|
||
<ul id="dropdown-list-SeismicActivity"
|
||
style="list-style-type: none; margin: 0; padding: 0;"></ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
{% endif %}
|
||
</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 src="{% static 'js/ol/ol-ext/ol-ext.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
<script src="{% static 'js/ol/layersStyles.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
<script src="{% static 'js/ol/mapCommonFuncs.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
<script src="{% static 'js/ol/timeSliderFuncs.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
<script>
|
||
document.addEventListener("DOMContentLoaded", async () => {
|
||
|
||
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);
|
||
});
|
||
}
|
||
|
||
|
||
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 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);
|
||
}
|
||
|
||
async function initializeMap() {
|
||
OSM = new ol.layer.Tile({
|
||
baseLayer: true,
|
||
source: new ol.source.OSM(), // Open street Map
|
||
})
|
||
OSM.set('title', 'OpenStreet Map')
|
||
// Источник данных для GTO
|
||
GTOSource = new ol.source.Vector();
|
||
|
||
// Слой для отображения GTO
|
||
GTOLayer = new ol.layer.Vector({
|
||
source: GTOSource,
|
||
style: GTOStyleFunction
|
||
});
|
||
GTOLayer.set('title', 'Горнотранспортное оборудование')
|
||
|
||
// Источник данных для Vlocation
|
||
VlocationSource = new ol.source.Vector();
|
||
|
||
// Слой для Vlocation
|
||
VlocationLayer = new ol.layer.Vector({
|
||
source: VlocationSource,
|
||
style: VlocationStyleFunction
|
||
})
|
||
VlocationLayer.set('title', 'Местоположение сотрудников')
|
||
|
||
SPSource = new ol.source.Vector();
|
||
SPLayer = new ol.layer.Vector({
|
||
source: SPSource,
|
||
style: SPStyleFunction
|
||
});
|
||
SPLayer.set('title', 'Сейсмические процессы')
|
||
initTimeSlider()
|
||
|
||
mineBorderLayer = new ol.layer.Vector({
|
||
source: new ol.source.Vector({
|
||
url: '/{{ prgr }}',
|
||
format: new ol.format.KML({extractStyles: false}),
|
||
|
||
}),
|
||
style: polygonStyleFunction,
|
||
});
|
||
mineBorderLayer.set('title', 'Границы ПРГР')
|
||
|
||
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('title', 'Ортофотоплан')
|
||
|
||
GTOZonePolygonsLayer = new ol.layer.Vector({
|
||
source: new ol.source.Vector({
|
||
url: '/gto/polygons/',
|
||
format: new ol.format.GeoJSON(),
|
||
}),
|
||
style: polygonBrownStyleFunction,
|
||
});
|
||
|
||
GTOZonePolygonsLayer.set('title', 'Зоны')
|
||
|
||
const staticLayers = [
|
||
GTOZonePolygonsLayer,
|
||
mineBorderLayer,
|
||
]
|
||
|
||
const dynamicLayers = [
|
||
SPLayer,
|
||
VlocationLayer,
|
||
GTOLayer,
|
||
]
|
||
|
||
async function fetchLayers() {
|
||
|
||
const response = await fetch('layers/')
|
||
const data = await response.json()
|
||
|
||
data["static_layers"].forEach(layer => {
|
||
const newLayer = createLayer(layer);
|
||
staticLayers.push(newLayer)
|
||
})
|
||
data["dynamic_layers"].forEach(layer => {
|
||
const newLayer = createLayer(layer);
|
||
dynamicLayers.push(newLayer)
|
||
})
|
||
const scanLayerExists = Boolean(parseInt('{{ scan_layer_enable }}'))
|
||
|
||
if (scanLayerExists) {
|
||
staticLayers.splice(0, 0, scanLayer)
|
||
}
|
||
return [
|
||
new ol.layer.Group({
|
||
title: 'Базовые слои',
|
||
openInLayerSwitcher: true,
|
||
layers: [OSM],
|
||
}),
|
||
new ol.layer.Group({
|
||
title: 'Статические слои',
|
||
openInLayerSwitcher: true,
|
||
layers: staticLayers,
|
||
}),
|
||
new ol.layer.Group({
|
||
title: 'Динамические слои',
|
||
openInLayerSwitcher: true,
|
||
layers: dynamicLayers,
|
||
}),
|
||
]
|
||
}
|
||
|
||
function createLayer(layer) {
|
||
let newLayer;
|
||
console.log(layer)
|
||
if (layer.layer_type === 'Tile') {
|
||
newLayer = new ol.layer.Tile({
|
||
source: new ol.source.XYZ({
|
||
url: layer.url,
|
||
}),
|
||
visible: layer.is_visible,
|
||
});
|
||
} else if (layer.layer_type === 'Vector') {
|
||
newLayer = new ol.layer.Vector({
|
||
source: new ol.source.Vector({
|
||
url: layer.url,
|
||
format: new ol.format.GeoJSON(),
|
||
}),
|
||
visible: layer.is_visible,
|
||
style: createStyleFromFeature
|
||
});
|
||
}
|
||
newLayer.set('title', layer.name)
|
||
newLayer.set('name', layer.name)
|
||
|
||
return newLayer
|
||
}
|
||
|
||
|
||
// Создание карты
|
||
map = new ol.Map({
|
||
target: 'map', // ID элемента, куда встроится карта
|
||
controls: [
|
||
new ol.control.ScaleLine(),
|
||
new ol.control.ZoomSlider()
|
||
],
|
||
layers: await fetchLayers(),
|
||
view: new ol.View({
|
||
center: ol.proj.fromLonLat([centerLat, centerLon]), // Центр карты
|
||
zoom: 12,
|
||
}),
|
||
});
|
||
|
||
const layerSwitcherInner = document.getElementById("LayerSwitcherInner")
|
||
const layersBtn = document.getElementById("layers-btn")
|
||
const layerSwitcher = new ol.control.LayerShop({
|
||
minibar: true,
|
||
target: layerSwitcherInner
|
||
})
|
||
|
||
document.getElementById('layers-btn').addEventListener("click", (event) => {
|
||
if (layerSwitcherInner.style.display === "block") {
|
||
layerSwitcherInner.style.display = "none"
|
||
} else {
|
||
layerSwitcherInner.style.display = "block"
|
||
}
|
||
layersBtn.classList.toggle("selected")
|
||
})
|
||
layerSwitcher.addControl(
|
||
new ol.control.Button({
|
||
html: "Создать слой",
|
||
handleClick: function () {
|
||
window.location.href = '{% url 'create_layer' %}'
|
||
}
|
||
}), 'bottom');
|
||
layerSwitcher.addControl(
|
||
new ol.control.Button({
|
||
html: "Редактировать слои",
|
||
handleClick: function () {
|
||
window.location.href = '{% url 'layers_list' %}'
|
||
}
|
||
}), 'bottom'
|
||
);
|
||
|
||
map.addControl(layerSwitcher)
|
||
|
||
const element = document.getElementById('popup')
|
||
// Всплывающее окно
|
||
popup = new ol.Overlay({
|
||
element: element,
|
||
positioning: 'bottom-center',
|
||
});
|
||
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]['Value'] + "%";
|
||
|
||
// Удаляем все возможные классы перед добавлением нового
|
||
elem.classList.remove("bg-success", "bg-warning", "bg-orange", "bg-danger");
|
||
|
||
// Добавляем нужный класс в зависимости от значения
|
||
if (75 <= data[item]['Value'] && data[item]['Value'] <= 100) {
|
||
elem.classList.add("bg-success");
|
||
} else if (50 <= data[item]['Value'] && data[item]['Value'] < 75) {
|
||
elem.classList.add("bg-warning");
|
||
} else if (25 <= data[item]['Value'] && data[item]['Value'] < 50) {
|
||
elem.classList.add("bg-orange");
|
||
} else if (data[item]['Value'] < 25) {
|
||
elem.classList.add("bg-danger");
|
||
}
|
||
|
||
// Заполняем выпадающее меню
|
||
const dropdownList = document.getElementById(`dropdown-list-${item}`);
|
||
if (dropdownList && data[item]['BadObjects'] && data[item]['BadObjects'].length > 0) {
|
||
dropdownList.innerHTML = data[item]['BadObjects'].map(obj => `
|
||
<li><a class="dropdown-item" href="${obj.url}">${obj.name}</a></li>
|
||
`).join('');
|
||
} else {
|
||
dropdownList.innerHTML = `<span style="text-align: center; width: 100%"> Нет данных.</span`
|
||
}
|
||
}
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error("Ошибка при получении данных:", error);
|
||
});
|
||
|
||
}
|
||
|
||
let toStart = document.querySelector('#toStart')
|
||
toStart.addEventListener('click', ev => {
|
||
map.setView(new ol.View({
|
||
center: ol.proj.fromLonLat([centerLat, centerLon]), // Центр карты
|
||
zoom: 12,
|
||
}))
|
||
})
|
||
|
||
|
||
document.querySelectorAll('.dropdown').forEach(dropdown => {
|
||
const dropdownIcon = dropdown.querySelector('.dropdown-icon');
|
||
})
|
||
await initializeMap();
|
||
})
|
||
|
||
</script>
|
||
|
||
|
||
{% endblock script_footer %}
|