diff --git a/apps/main/templates/main_index.html b/apps/main/templates/main_index.html
index 3ded26b..94ebf12 100644
--- a/apps/main/templates/main_index.html
+++ b/apps/main/templates/main_index.html
@@ -2,15 +2,279 @@
{% load static %}
{% load mysettings %}
+{% block header_link %}
+
+
+ {# #}
+ {# #}
+ {# #}
+ {# #}
+ {# #}
+
+{% endblock header_link %}
{% block content %}
+
+
+
+
{% endblock %}
-
{% block script_footer %}
+
+
+
+ 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: `
+
+ Имя: ${feature.get('name') || 'Нет имени'}
+ Координаты: ${feature.get('lat')} ${feature.get('lon')}
+ Время координат: ${feature.get('time') || 'Нет времени'}
+
+ `,
+ });
+
+ // Отображение 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;
+
+
{% endblock script_footer %}
diff --git a/apps/main/views/views_main.py b/apps/main/views/views_main.py
index 756d208..37af19f 100644
--- a/apps/main/views/views_main.py
+++ b/apps/main/views/views_main.py
@@ -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())
-
-