diff --git a/apps/main/templates/main_index.html b/apps/main/templates/main_index.html
index 107eb26..7c74137 100644
--- a/apps/main/templates/main_index.html
+++ b/apps/main/templates/main_index.html
@@ -20,6 +20,34 @@
.ol-layer-list {
list-style: none;
}
+
+ #time-slider {
+ width: 200px;
+ height: 5px;
+ background: #ccc;
+ outline: none;
+ border-radius: 5px;
+ -webkit-appearance: none;
+ appearance: none;
+ }
+
+ #time-slider::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 15px;
+ height: 15px;
+ background: #007bff;
+ border-radius: 50%;
+ cursor: pointer;
+ }
+
+ #time-slider::-moz-range-thumb {
+ width: 15px;
+ height: 15px;
+ background: #007bff;
+ border-radius: 50%;
+ cursor: pointer;
+ }
{% endblock header_link %}
@@ -35,6 +63,12 @@
Вернуться на разрез
+
@@ -71,6 +105,112 @@
let centerLat = '{{lon}}'
let centerLon = '{{lat}}'
+ const seismDays = parseInt("{{ seism_days }}");
+ 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() {
+ // Установка минимального и максимального значений слайдера
+ slider.min = 0;
+ slider.max = 100;
+
+ // Вычисление минимальной даты (на seismDays дней меньше текущей)
+ const startDate = new Date();
+ startDate.setDate(startDate.getDate() - seismDays); // seismDays передается из Django
+
+ // Текущая дата
+ const endDate = new Date();
+
+ // Установка начального значения слайдера (по умолчанию - текущая дата)
+ const initialDate = new Date();
+ const sliderValue = calculateSliderValueFromStartDate(initialDate, startDate, endDate);
+ slider.value = sliderValue;
+
+ // Форматирование даты в российский формат
+ 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);
+ });
+ }
+
const getGTOMarkerText = function (feature) {
const statemum = feature.get('garagenum')
if (statemum) {
@@ -351,6 +491,7 @@
style: SPStyleFunction
});
SPLayer.set('name', 'Сейсмические процессы')
+ initTimeSlider()
mineBorderLayer = new ol.layer.Vector({
source: new ol.source.Vector({
@@ -382,12 +523,12 @@
scanLayer.set('name', 'Ортофотоплан')
GTOZonePolygonsLayer = new ol.layer.Vector({
- source: new ol.source.Vector({
- url: '/gto/polygons/',
- format: new ol.format.GeoJSON(),
- }),
- style: polygonBrownStyleFunction,
- });
+ source: new ol.source.Vector({
+ url: '/gto/polygons/',
+ format: new ol.format.GeoJSON(),
+ }),
+ style: polygonBrownStyleFunction,
+ });
GTOZonePolygonsLayer.set('name', 'Зоны')
@@ -714,22 +855,9 @@
})
})
- 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)
- }
- })
- })
+
+ {#fetchEarthquakes()#}
+
{#fetch('/gto/polygons/', {#}
{# method: 'POST',#}
{# headers: {'X-CSRFToken': csrftoken},#}
@@ -748,7 +876,6 @@
zoom: 12,
}))
})
-
window.onload = initializeMap;
diff --git a/apps/main/views/views_main.py b/apps/main/views/views_main.py
index 6b3c6a1..e38c1ee 100644
--- a/apps/main/views/views_main.py
+++ b/apps/main/views/views_main.py
@@ -16,6 +16,7 @@ from django.views.decorators.cache import never_cache
from django.db.models import Avg, Max, Min
from apps.general.views import settingsmodule
+from apps.general.views.settingsmodule import get_settings
from apps.util import generalmodule
from sabron.util import logging
@@ -29,8 +30,10 @@ def mainindex(request):
'86.10111978605353'))) # долгота центра
lat = str(float(settingsmodule.get_settings('latitude',
'55.344251210827814'))) # широта
+ seism_days = get_settings("seism_days", "30")
prgr = settingsmodule.get_settings('prgr', '')
- scan_layer_enable = settingsmodule.get_settings('scan_layer_enable', '0')
+ scan_layer_enable = settingsmodule.get_settings(
+ 'scan_layer_enable', '0')
context = generalmodule.get_context_template()
context.update({
'lon': lon.replace(',', '.'),
@@ -38,6 +41,7 @@ def mainindex(request):
'prgr': prgr,
'scan_layer_enable': scan_layer_enable,
'updatepage': True,
+ "seism_days": seism_days
})
return render(request, 'main_index.html', context)
except Exception as err:
diff --git a/apps/seismicproc/views/views_main.py b/apps/seismicproc/views/views_main.py
index 2ff2d91..87279ee 100644
--- a/apps/seismicproc/views/views_main.py
+++ b/apps/seismicproc/views/views_main.py
@@ -17,6 +17,7 @@ from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.models import User
+from apps.general.views.settingsmodule import get_settings
from apps.seismicproc.models.model_earthquake import Earthquake
from apps.seismicproc.forms.form_earthquake import EarthquakeForm
@@ -146,14 +147,21 @@ def main_index(request):
def earthquake_list(request):
try:
- two_days_ago = datetime.now() - timedelta(days=2)
- earthquakes = (Earthquake.objects.
- filter(date_time__gt=two_days_ago).
- order_by("-date_time").
- all())
+
+ # Получение параметра даты из запроса
+ selected_date_str = request.GET.get('date')
+ if selected_date_str:
+ selected_date = datetime.strptime(selected_date_str, "%Y-%m-%d")
+ else:
+ selected_date = datetime.now()
+
+ # Фильтрация землетрясений по дате
+ earthquakes = Earthquake.objects.filter(
+ date_time__gte=selected_date
+ ).order_by("-date_time")
+
res = []
for earthquake in earthquakes:
- # Формула для вычисления радиуса землетрясения
res.append({
'id': earthquake.id,
'time': earthquake.date_time.strftime("%d.%m.%Y %H:%M:%S"),
@@ -164,6 +172,8 @@ def earthquake_list(request):
'region': earthquake.region,
'source': earthquake.source,
})
+
return JsonResponse(res, safe=False)
except Exception as err:
- logging.error(traceback.format_exc())
\ No newline at end of file
+ logging.error(traceback.format_exc())
+ return JsonResponse({'error': 'Internal Server Error'}, status=500)
\ No newline at end of file