Перенес карту из ГТО на главную страницу

This commit is contained in:
zakhy 2025-01-10 09:30:05 +07:00
parent 8bde12f275
commit 84fa815d8c
2 changed files with 278 additions and 9 deletions

View File

@ -2,15 +2,279 @@
{% 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' %}">
{# <script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-core.js"></script>#}
{# <script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-service.js"></script>#}
{# <script type="text/javascript" src="https://js.api.here.com/v3/3.1/mapsjs-ui.js"></script>#}
{# <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' %}">
{% endblock header_link %}
{% block content %}
<section class="content text-sm">
<form id="list_acs" method="post" class="form-horizontal">
{% csrf_token %}
<input id="id_acs" type="hidden" value="None" name="id">
<input id="cmd" type="hidden" value="None" name="cmd">
<div class="row">
<div class="col-md-12">
<div class="card card-primary card-outline mt-1">
<div class="card-body">
<div class="tab-content">
<div class="row">
<div class="col-md-12">
<ul class="nav nav-tabs" id="custom-content-above-tab" role="tablist">
<li class="nav-item">
<a class="nav-link active " id="custom-content-above-profile-tab"
data-toggle="pill" href="#custom-content-map" role="tab"
aria-controls="custom-content-map" aria-selected="true">Интерактивная карта</a>
</li>
</ul>
<div class="tab-content" id="custom-content-above-tabContent">
<div class="tab-pane fade active show" id="custom-content-map"
role="tabpanel" aria-labelledby="custom-content-map-tab">
<div class="card">
<div class="card-body table-responsive p-0"
style="height: 75vh; padding-left: 0;">
<div id="map">
<div id="popup"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</section>
{% endblock %}
{% block script_footer %}
<script src="{% static 'js/ol/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<script>
const getText = function (feature) {
let text = feature.get('statenum');
return text;
};
const createTextStyle = function (feature, resolution) {
const size = '14px';
const height = '1';
const weight = 'bold';
const font = weight + ' ' + size + '/' + height + ' ' + 'Arial';
const fillColor = '#000';
const borderWidth = parseInt('0.1', 10);
<script>
const backgroundFill = '#fff'
const backgroundStroke = '#000'
</script>
return new ol.style.Text({
textAlign: 'center',
textBaseline: 'middle',
font: font,
text: getText(feature, resolution),
fill: new ol.style.Fill({color: fillColor}),
offsetX: 0,
offsetY: -30,
placement: 'point',
maxAngle: '0.7853981633974483',
overflow: 'false',
rotation: parseFloat('0'),
backgroundFill: new ol.style.Fill({color: backgroundFill}),
backgroundStroke: new ol.style.Stroke({color: backgroundStroke, width: borderWidth}),
padding: [5, 5, 5, 5],
});
};
function pointStyleFunction(feature, resolution) {
return new ol.style.Style({
image: new ol.style.Icon({
src: '/static/img/belaz.png',
scale: 0.1, // Масштаб иконки
}),
text: createTextStyle(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);
}
let map, GTOLayer, GTOSource, popup, m_markers = {};
function initializeMap() {
// Источник данных для маркеров
GTOSource = new ol.source.Vector();
// Слой для отображения маркеров
GTOLayer = new ol.layer.Vector({
source: GTOSource,
style: pointStyleFunction
});
// Создание карты
map = new ol.Map({
target: 'map', // ID элемента, куда встроится карта
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(), // Open street Map
}),
GTOLayer,
],
view: new ol.View({
center: ol.proj.fromLonLat(['{{lon}}', '{{lat}}']), // Центр карты
zoom: 14,
}),
});
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);
// Создание нового popover
popover = new bootstrap.Popover(element, {
placement: 'top', // Расположение popover
html: true, // Поддержка HTML-содержимого
content: `
<div>
<span><strong>Имя: </strong>${feature.get('name') || 'Нет имени'}</span><br>
<span><strong>Координаты: </strong>${feature.get('lat')} ${feature.get('lon')}</span><br>
<span><strong>Время координат: </strong>${feature.get('time') || 'Нет времени'}</span>
</div>
`,
});
// Отображение popover
popover.show();
});
map.on('movestart', disposePopover);
// Загрузка маркеров
updateMarkers();
setInterval(updateMarkers, 5000)
}
function addMarker(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
});
GTOSource.addFeature(feature);
m_markers[equipment.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 (m_markers[equipment.id]) {
const marker = m_markers[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 {
// Создаем новый маркер, если его ещё нет
addMarker(equipment);
}
});
});
}
window.onload = initializeMap;
</script>
{% endblock script_footer %}

View File

@ -15,7 +15,7 @@ from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.db.models import Avg, Max, Min
from apps.general.views import settingsmodule
from apps.util import generalmodule
from sabron.util import logging
@ -25,12 +25,17 @@ from sabron.util import logging
def mainindex(request):
try:
if request.method == "GET":
lon = str(float(settingsmodule.get_settings('longitude',
'86.10111978605353'))) # долгота центра
lat = str(float(settingsmodule.get_settings('latitude',
'55.344251210827814'))) # широта
context = generalmodule.get_context_template()
context.update({
'updatepage':True,
})
return render(request, 'main_index.html',context)
'lon': lon.replace(',', '.'),
'lat': lat.replace(',', '.'),
'updatepage': True,
})
return render(request, 'main_index.html', context)
except Exception as err:
logging.error(traceback.format_exc())