Сейсмика и интерактивные элементы

This commit is contained in:
zakhy 2025-01-13 15:43:29 +07:00
parent 2ba3a078ad
commit 34442405ee

View File

@ -12,6 +12,19 @@
{# <script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"></script>#}
{# <link rel="stylesheet" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css">#}
<link rel="stylesheet" href="{% static 'js/ol/theme/default/ol.css' %}">
<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 %}
@ -21,6 +34,7 @@
<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>
@ -35,6 +49,7 @@
<script src="{% static 'js/ol/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<script>
let OSM = {};
let map, popup = {}
// ГТО
let GTOSource = {}
@ -51,6 +66,9 @@
let mineBorderLayer = {}
let centerLat = '{{lon}}'
let centerLon = '{{lat}}'
const getGTOMarkerText = function (feature) {
return feature.get('statenum');
};
@ -116,6 +134,16 @@
})
}
function SPStyleFunction(feature, resolution) {
return new ol.style.Style({
image: new ol.style.Icon({
src: '/static/img/earthquake.png',
width: 25,
height: 30
})
})
}
function polygonStyleFunction(feature, resolution) {
return new ol.style.Style({
stroke: new ol.style.Stroke({
@ -163,6 +191,10 @@
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();
@ -171,6 +203,7 @@
source: GTOSource,
style: GTOStyleFunction
});
GTOLayer.set('name', 'Горнотранспортное оборудование')
// Источник данных для Vlocation
VlocationSource = new ol.source.Vector();
@ -180,7 +213,14 @@
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({
@ -190,24 +230,126 @@
}),
style: polygonStyleFunction,
});
mineBorderLayer.set('name', 'Границы ПРГР')
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);
}
}
}
// Создание карты
map = new ol.Map({
target: 'map', // ID элемента, куда встроится карта
controls: [
{#new ol.control.Zoom(),#}
new ol.control.FullScreen(),
new LayerSwitcherControl(),
new ol.control.ScaleLine(),
new ol.control.ZoomSlider()
],
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(), // Open street Map
}),
OSM,
mineBorderLayer,
GTOLayer,
SPLayer,
VlocationLayer,
],
view: new ol.View({
center: ol.proj.fromLonLat(['{{lon}}', '{{lat}}']), // Центр карты
center: ol.proj.fromLonLat([centerLat, centerLon]), // Центр карты
zoom: 12,
}),
});
const element = document.getElementById('popup')
// Всплывающее окно
popup = new ol.Overlay({
@ -307,6 +449,62 @@
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
}
@ -369,6 +567,22 @@
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',
@ -410,11 +624,36 @@
})
})
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 %}