test/apps/main/templates/main_index.html

685 lines
27 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;
}
</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="test" 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>
</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 centerLat = '{{lon}}'
let centerLon = '{{lat}}'
const getGTOMarkerText = function (feature) {
const statemum = feature.get('statenum')
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],
});
};
function GTOStyleFunction(feature, resolution) {
return new ol.style.Style({
image: new ol.style.Icon({
src: '/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);
}
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', 'Сейсмические процессы')
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: '/static/img/tiles/{z}/{x}/{y}.png',
}),
extent: ol.proj.transformExtent(
[86.639393, 53.959368, 86.698046, 54.004628], // [minLon, minLat, maxLon, maxLat]
'EPSG:4326', // Исходная проекция
'EPSG:3857' // Целевая проекция
)
});
scanLayer.set('name', 'Ортофотоплан')
const layers = [
OSM,
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 "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,
model: equipment.model
});
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('/seismicproc/earthquakes/')
.then(response => response.json())
.then(data => {
data.forEach(earthquake => {
if (SPMarkers[earthquake.id]) {
const marker = SPMarkers[earthquake.id]
const currentCoordinates = marker.getGeometry().getCoordinates();
const newCoordinates = ol.proj.fromLonLat([earthquake.lon, earthquake.lat]);
if (currentCoordinates[0] !== newCoordinates[0] || currentCoordinates[1] !== newCoordinates[1]) {
moveMarker(marker, newCoordinates); // Плавное перемещение
}
} else {
addSPMarker(earthquake)
}
})
})
}
let test = document.querySelector('#test')
test.addEventListener('click', ev => {
map.setView(new ol.View({
center: ol.proj.fromLonLat([centerLat, centerLon]), // Центр карты
zoom: 12,
}))
})
window.onload = initializeMap;
</script>
{% endblock script_footer %}