Промежуточный этап глобальной карты 2
20
positioning/apps/eps/migrations/0006_alter_tag_date_time.py
Normal file
@ -0,0 +1,20 @@
|
||||
# Generated by Django 4.2.19 on 2025-03-31 10:17
|
||||
|
||||
import django.utils.timezone
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("eps", "0005_tagdate_street"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="tag",
|
||||
name="date_time",
|
||||
field=models.DateTimeField(
|
||||
default=django.utils.timezone.now, verbose_name="Время"
|
||||
),
|
||||
),
|
||||
]
|
||||
@ -0,0 +1,27 @@
|
||||
# Generated by Django 4.2.19 on 2025-03-31 10:20
|
||||
|
||||
import django.utils.timezone
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("eps", "0006_alter_tag_date_time"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="tag",
|
||||
name="date_time_street",
|
||||
field=models.DateTimeField(
|
||||
default=django.utils.timezone.now, verbose_name="Время (Улица)"
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="tag",
|
||||
name="date_time",
|
||||
field=models.DateTimeField(
|
||||
default=django.utils.timezone.now, verbose_name="Время (3d)"
|
||||
),
|
||||
),
|
||||
]
|
||||
@ -0,0 +1,33 @@
|
||||
# Generated by Django 4.2.19 on 2025-03-31 10:27
|
||||
|
||||
import django.utils.timezone
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("eps", "0007_tag_date_time_street_alter_tag_date_time"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="tag",
|
||||
name="date_time",
|
||||
field=models.DateTimeField(
|
||||
blank=True,
|
||||
default=django.utils.timezone.now,
|
||||
null=True,
|
||||
verbose_name="Время (3d)",
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="tag",
|
||||
name="date_time_street",
|
||||
field=models.DateTimeField(
|
||||
blank=True,
|
||||
default=django.utils.timezone.now,
|
||||
null=True,
|
||||
verbose_name="Время (Улица)",
|
||||
),
|
||||
),
|
||||
]
|
||||
@ -1,8 +1,9 @@
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from apps.base.base_service import BaseService
|
||||
from apps.eps.models.zone.model_zones import Zone
|
||||
from django.db import models
|
||||
from django.utils import timezone
|
||||
|
||||
|
||||
class Tag(models.Model):
|
||||
@ -35,7 +36,18 @@ class Tag(models.Model):
|
||||
alt = models.FloatField(default=0.0, verbose_name="alt")
|
||||
|
||||
date_time = models.DateTimeField(
|
||||
auto_now=False, default=datetime.now, verbose_name="Время"
|
||||
auto_now=False,
|
||||
default=timezone.now,
|
||||
verbose_name="Время (3d)",
|
||||
null=True,
|
||||
blank=True,
|
||||
)
|
||||
date_time_street = models.DateTimeField(
|
||||
auto_now=False,
|
||||
default=timezone.now,
|
||||
verbose_name="Время (Улица)",
|
||||
null=True,
|
||||
blank=True,
|
||||
)
|
||||
active = models.BooleanField(
|
||||
verbose_name="Активный", null=False, default=True, blank=True
|
||||
@ -58,6 +70,28 @@ class Tag(models.Model):
|
||||
self.descr = self.sn
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
@property
|
||||
def worker_name(self) -> str:
|
||||
if hasattr(self, "worker") and self.worker:
|
||||
return self.worker.name
|
||||
else:
|
||||
return "Не назначен"
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"name": self.worker_name,
|
||||
"sn": self.sn,
|
||||
"lat": self.lat,
|
||||
"lon": self.lon,
|
||||
"alt": self.alt,
|
||||
"date_time": BaseService.convert_to_local_time(
|
||||
self.date_time_street
|
||||
).strftime("%d.%m.%Y %H:%M:%S")
|
||||
if self.date_time_street
|
||||
else "",
|
||||
}
|
||||
|
||||
class Meta: # отображение в админики
|
||||
ordering = ("name",)
|
||||
verbose_name = "тэг"
|
||||
|
||||
18
positioning/apps/main/migrations/0003_building_zones.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.19 on 2025-03-31 07:48
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("eps", "0005_tagdate_street"),
|
||||
("main", "0002_building_active"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="building",
|
||||
name="zones",
|
||||
field=models.ManyToManyField(blank=True, to="eps.zone"),
|
||||
),
|
||||
]
|
||||
@ -1,9 +1,16 @@
|
||||
from apps.eps.models.zone.model_zones import Zone
|
||||
from django.contrib.gis.db import models
|
||||
|
||||
|
||||
class Building(models.Model):
|
||||
"""
|
||||
Модель здания.
|
||||
На карте на нем будет отображаться, сколько тегов в нем находится.
|
||||
"""
|
||||
|
||||
name = models.CharField(max_length=128)
|
||||
polygon = models.PolygonField()
|
||||
zones = models.ManyToManyField(Zone, blank=True)
|
||||
active = models.BooleanField(default=True)
|
||||
|
||||
def __str__(self) -> str:
|
||||
|
||||
@ -13,6 +13,8 @@
|
||||
let PolygonsSource = {}
|
||||
let PolygonsMarkers = {}
|
||||
|
||||
let polygonCounts = {};
|
||||
|
||||
let popup = {}
|
||||
const propertiesTranslate = {
|
||||
name: "Имя",
|
||||
@ -160,7 +162,7 @@
|
||||
});
|
||||
PolygonsLayer = new ol.layer.Vector({
|
||||
source: new ol.source.Vector({
|
||||
url: '/buildings/polygons/',
|
||||
url: '{% url "main:poligon_list_api" %}',
|
||||
format: new ol.format.GeoJSON(),
|
||||
}),
|
||||
style: polygonBrownStyleFunction,
|
||||
@ -179,9 +181,13 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Модифицируем функцию getPolygonText
|
||||
const getPolygonText = function (feature) {
|
||||
return feature.get('name')
|
||||
const polygonId = feature.get('pk');
|
||||
const count = polygonCounts[polygonId] || 0;
|
||||
return `${feature.get('name')} (${count})`;
|
||||
};
|
||||
|
||||
const createTextStyle = function (feature, resolution) {
|
||||
const zoom = map.getView().getZoom();
|
||||
const font = 'bold' + ' ' + zoom + 'px' + '/' + '1' + ' ' + 'Arial';
|
||||
@ -263,7 +269,7 @@
|
||||
}
|
||||
|
||||
function updateMarkers() {
|
||||
fetch('street_pos/map/update_object/')
|
||||
fetch('{% url "street_pos:tags_list_api" %}')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
data.items.forEach(worker => {
|
||||
@ -285,6 +291,18 @@
|
||||
}
|
||||
});
|
||||
});
|
||||
fetch('{% url "main:poligon_count_api" %}') // Замените на ваш endpoint
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
// Обновляем данные о количестве
|
||||
data.items.forEach(item => {
|
||||
polygonCounts[item.id] = item.count;
|
||||
});
|
||||
// Обновляем стили полигонов, чтобы текст перерисовался
|
||||
PolygonsLayer.getSource().forEachFeature(feature => {
|
||||
feature.changed();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -3,9 +3,11 @@
|
||||
{% load settings_tag %}
|
||||
|
||||
{% block header_link %}
|
||||
<link rel="stylesheet" href="{% static 'street_pos/openLayers/theme/default/ol.css' %}?ver={% settings_value 'APP_VERSION' %}">
|
||||
|
||||
<link rel="stylesheet" href="{% static 'main/main.css' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static '/openLayers/theme/default/ol.css' %}?ver={% settings_value 'APP_VERSION' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static '/openLayers/theme/map-widgets.css' %}?ver={% settings_value 'APP_VERSION' %}">
|
||||
<link rel="stylesheet" href="{% static '/main/main.css' %}?ver={% settings_value 'APP_VERSION' %}">
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
@ -16,7 +18,18 @@
|
||||
<div class="col-12">
|
||||
<div class="card mb-0">
|
||||
<div class="card-body p-0 card-body-full-height">
|
||||
<div id="map" class="w-100 h-100">
|
||||
<div id="map" class="h-100 w-100">
|
||||
<button type="button" id="toStart" 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 id="LayerSwitcher">
|
||||
<div class="layers-btn-container">
|
||||
<div id="layers-btn"></div>
|
||||
</div>
|
||||
<div id="LayerSwitcherInner"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div> <!-- /.card-body -->
|
||||
</div> <!-- /.card -->
|
||||
@ -26,10 +39,176 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'street_pos/openLayers/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VERSION' %}"></script>
|
||||
{# <script src="{% static 'street_pos/openLayers/ol-ext/ol-ext.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>#}
|
||||
<script src="{% static '/openLayers/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/ol-ext/ol-ext.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/map/map-core.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/map/map-layer-switcher.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/map/map-marker-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/map/map-created-layer-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
{% endblock %}
|
||||
|
||||
{% block script_footer %}
|
||||
{% include 'main/includes/map_script.html' with lat=map_center_lat lon=map_center_lon polygons=polygons %}
|
||||
<script>
|
||||
let polygonsLayer
|
||||
let workerLayer
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
// Инициализация карты
|
||||
const mapCore = new MapCore('map', {
|
||||
center: ['{{map_center_lon}}', '{{map_center_lat}}'],
|
||||
zoom: 12
|
||||
});
|
||||
|
||||
await mapCore.initialize();
|
||||
|
||||
// Инициализация переключателя слоев
|
||||
const LayerSwitcherInner = document.getElementById('LayerSwitcherInner')
|
||||
const layerSwitcher = new LayerSwitcher(mapCore, LayerSwitcherInner);
|
||||
|
||||
workerLayer = new ol.layer.Vector({source: new ol.source.Vector()});
|
||||
workerLayer.set('title', 'Местоположение персонала')
|
||||
const workerManager = new MarkerManager(workerLayer, VlocationStyleFunction);
|
||||
|
||||
mapCore.addLayer(workerLayer, 'dynamic');
|
||||
|
||||
polygonsLayer = new ol.layer.Vector({
|
||||
source: new ol.source.Vector({
|
||||
url: '{% url 'main:poligon_list_api' %}',
|
||||
format: new ol.format.GeoJSON(),
|
||||
}),
|
||||
style: polygonBrownStyleFunction,
|
||||
});
|
||||
polygonsLayer.set('title', 'Здания')
|
||||
mapCore.addLayer(polygonsLayer, 'static')
|
||||
|
||||
let polygonCounts = {};
|
||||
|
||||
// Кнопка возврата
|
||||
document.getElementById('toStart').addEventListener('click', () => {
|
||||
mapCore.map.getView().animate({
|
||||
center: ol.proj.fromLonLat(['{{lon}}', '{{lat}}']),
|
||||
zoom: 12
|
||||
});
|
||||
});
|
||||
|
||||
// Функция для обновления маркеров
|
||||
async function updateMarkers() {
|
||||
// Обновление работников
|
||||
const workersData = await fetch('{% url 'street_pos:tags_list_api' %}')
|
||||
.then(r => r.json());
|
||||
|
||||
|
||||
workersData.items.forEach(worker => {
|
||||
if (workerManager.markers[worker.id]) {
|
||||
workerManager.animateMarker(worker.id, [worker.lon, worker.lat]);
|
||||
workerManager.updateMarker(worker.id, [worker.lon, worker.lat], worker);
|
||||
} else {
|
||||
workerManager.addMarker(worker.id, [worker.lon, worker.lat], worker);
|
||||
}
|
||||
});
|
||||
const response = await fetch('{% url "main:poligon_count_api" %}') // Замените на ваш endpoint
|
||||
const json = await response.json()
|
||||
json.items.forEach(item => {
|
||||
polygonCounts[item.id] = item.count;
|
||||
});
|
||||
polygonsLayer.getSource().forEachFeature(feature => {
|
||||
feature.changed();
|
||||
});
|
||||
}
|
||||
|
||||
await updateMarkers();
|
||||
setInterval(updateMarkers, 3000);
|
||||
|
||||
function createWorkersTableRow(worker) {
|
||||
const tr = document.createElement('tr')
|
||||
|
||||
const tdWorkerID = document.createElement('td')
|
||||
tdWorkerID.textContent = worker.name
|
||||
|
||||
// Переход по клику на координату
|
||||
const tdWorkerCoord = document.createElement('td')
|
||||
const showCoordButton = document.createElement('a')
|
||||
showCoordButton.className = 'worker-show-button'
|
||||
showCoordButton.style.cursor = 'pointer'
|
||||
showCoordButton.dataset.worker_id = worker.id
|
||||
showCoordButton.textContent = "Показать на карте"
|
||||
showCoordButton.addEventListener('click', (ev) => {
|
||||
const feature = workerManager.markers[ev.target.dataset.worker_id];
|
||||
const featureCoords = feature.getGeometry().getCoordinates();
|
||||
// Устанавливаем новый вид карты
|
||||
mapCore.map.getView().animate({
|
||||
center: featureCoords,
|
||||
zoom: 17,
|
||||
duration: 1000,
|
||||
});
|
||||
setTimeout(() => {
|
||||
showPopover(feature, featureCoords)
|
||||
}, 1001)
|
||||
});
|
||||
tdWorkerCoord.appendChild(showCoordButton)
|
||||
|
||||
switch (worker.condition) {
|
||||
case "ok":
|
||||
tdWorkerCoord.style.backgroundColor = ''
|
||||
break
|
||||
case "warning":
|
||||
tdWorkerCoord.style.backgroundColor = 'var(--warning)'
|
||||
break
|
||||
case "danger":
|
||||
tdWorkerCoord.style.backgroundColor = '#bebebe'
|
||||
break
|
||||
}
|
||||
|
||||
tr.appendChild(tdWorkerID)
|
||||
tr.appendChild(tdWorkerCoord)
|
||||
return tr
|
||||
}
|
||||
|
||||
function VlocationStyleFunction(feature, resolution) {
|
||||
return new ol.style.Style({
|
||||
image: new ol.style.Icon({
|
||||
src: '/static/img/worker.png',
|
||||
width: 25,
|
||||
height: 30
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function polygonBrownStyleFunction(feature, resolution) {
|
||||
return new ol.style.Style({
|
||||
stroke: new ol.style.Stroke({
|
||||
color: 'rgb(199,136,10)',
|
||||
width: 2,
|
||||
}),
|
||||
fill: new ol.style.Fill({
|
||||
color: 'rgba(199,136,10, 0.6)',
|
||||
}),
|
||||
text: createTextStyle(feature, resolution)
|
||||
});
|
||||
}
|
||||
|
||||
function getPolygonText(feature) {
|
||||
const polygonId = feature.get('pk');
|
||||
const count = polygonCounts[polygonId] || 0;
|
||||
return `${feature.get('name')} \n (${count})`;
|
||||
}
|
||||
|
||||
function createTextStyle(feature, resolution) {
|
||||
const zoom = mapCore.map.getView().getZoom();
|
||||
const font = 'bold' + ' ' + zoom + 'px' + '/' + '1' + ' ' + 'Arial';
|
||||
return new ol.style.Text({
|
||||
textAlign: 'center',
|
||||
textBaseline: 'middle',
|
||||
font: font,
|
||||
text: getPolygonText(feature),
|
||||
fill: new ol.style.Fill({color: '#000'}),
|
||||
placement: 'point',
|
||||
scale: 1,
|
||||
overflow: 'false',
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
from apps.main.views.views_api import PolygonsApiView
|
||||
from apps.main.views.views_api import PolygonsApiView, PolygonsTagsCountApiView
|
||||
from apps.main.views.views_page import MainIndexView
|
||||
from django.urls import path
|
||||
|
||||
@ -6,5 +6,10 @@ app_name = "main"
|
||||
|
||||
urlpatterns = [
|
||||
path("", MainIndexView.as_view(), name="main_index"),
|
||||
path("buildings/polygons/", PolygonsApiView.as_view()),
|
||||
path("buildings/polygons/", PolygonsApiView.as_view(), name="poligon_list_api"),
|
||||
path(
|
||||
"buildings/polygons/count/",
|
||||
PolygonsTagsCountApiView.as_view(),
|
||||
name="poligon_count_api",
|
||||
),
|
||||
]
|
||||
|
||||
@ -1,14 +1,40 @@
|
||||
import json
|
||||
from datetime import timedelta
|
||||
|
||||
from apps.eps.models.tags.model_tags import Tag
|
||||
from apps.main.models.model_building import Building
|
||||
from django.core.serializers import serialize
|
||||
from django.http import HttpRequest, JsonResponse
|
||||
from django.utils import timezone
|
||||
from django.views import View
|
||||
|
||||
|
||||
class PolygonsApiView(View):
|
||||
def get(self, request: HttpRequest) -> JsonResponse:
|
||||
data = serialize(
|
||||
"geojson", Building.objects.all(), geometry_field="polygon", fields=["name"]
|
||||
"geojson",
|
||||
Building.objects.filter(active=True),
|
||||
geometry_field="polygon",
|
||||
fields=["name", "pk"],
|
||||
)
|
||||
return JsonResponse(json.loads(data))
|
||||
|
||||
|
||||
class PolygonsTagsCountApiView(View):
|
||||
def get(self, request: HttpRequest) -> JsonResponse:
|
||||
buildings = Building.objects.filter(active=True)
|
||||
items: list = []
|
||||
res = {
|
||||
"error": "",
|
||||
"status": 0,
|
||||
"total": 0,
|
||||
"items": items,
|
||||
}
|
||||
for building in buildings:
|
||||
zones = building.zones.all()
|
||||
tags = Tag.objects.filter(
|
||||
zone__in=zones, date_time__gt=timezone.now() - timedelta(minutes=5)
|
||||
)
|
||||
tags_count = tags.count()
|
||||
items.append({"id": building.id, "count": tags_count})
|
||||
return JsonResponse(res)
|
||||
|
||||
@ -7,6 +7,7 @@ from django.db.models import QuerySet
|
||||
|
||||
class StreetMapRepository(TagRepository):
|
||||
def __init__(self, model: Tag = Tag) -> None:
|
||||
super().__init__(model)
|
||||
self.model = model
|
||||
|
||||
def filter(self, **kwargs: Any) -> QuerySet:
|
||||
|
||||
@ -5,35 +5,20 @@ from base.base_service import BaseService
|
||||
|
||||
|
||||
class StreetMapService(BaseService):
|
||||
def __init__(self, repository: StreetMapRepository = StreetMapRepository()) -> None:
|
||||
self.repository = repository or StreetMapRepository()
|
||||
def __init__(self, repository: StreetMapRepository = None):
|
||||
self.repository = (
|
||||
repository if repository is not None else StreetMapRepository()
|
||||
)
|
||||
|
||||
def get_tags(self) -> dict:
|
||||
offset = timedelta(days=2)
|
||||
now = self.get_current_time()
|
||||
timeout = now - offset
|
||||
data = self.repository.filter(date_time__gte=timeout, is_street=True)
|
||||
tag_mas: list = []
|
||||
res = {
|
||||
data = self.repository.filter(date_time_street__gte=timeout, is_street=True)
|
||||
|
||||
return {
|
||||
"error": "",
|
||||
"status": 0,
|
||||
"total": 0,
|
||||
"items": tag_mas,
|
||||
"total": data.count(),
|
||||
"items": [tag.to_dict() for tag in data],
|
||||
}
|
||||
|
||||
for tag in data:
|
||||
tag_mas.append(
|
||||
{
|
||||
"id": tag.worker.id if tag.worker else tag.id,
|
||||
"name": tag.worker.name if tag.worker else tag.name,
|
||||
"sn": tag.sn,
|
||||
"lat": tag.lat,
|
||||
"lon": tag.lon,
|
||||
"alt": tag.alt,
|
||||
"date_time": self.convert_to_local_time(tag.date_time).strftime(
|
||||
"%d.%m.%Y %H:%M:%S"
|
||||
),
|
||||
}
|
||||
)
|
||||
res["total"] = data.count()
|
||||
return res
|
||||
|
||||
@ -4,5 +4,5 @@ from django.urls import path
|
||||
|
||||
urlpatterns = [
|
||||
path("", MapView.as_view(), name="street_map"),
|
||||
path("update_object/", TagCoordApiView.as_view(), name="tags_ajax"),
|
||||
path("update_object/", TagCoordApiView.as_view(), name="tags_list_api"),
|
||||
]
|
||||
|
||||
@ -5,6 +5,7 @@ import traceback
|
||||
from typing import Any
|
||||
|
||||
from apps.street_pos.services.map.service import StreetMapService
|
||||
from django.conf import settings
|
||||
from django.http import HttpRequest, JsonResponse
|
||||
from django.views import View
|
||||
|
||||
@ -14,7 +15,17 @@ logger = logging.getLogger("mfss")
|
||||
class TagCoordApiView(View):
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.service = StreetMapService() # Dependency injection
|
||||
self.service = StreetMapService()
|
||||
|
||||
def _error_response(self, error_msg: str) -> JsonResponse:
|
||||
return JsonResponse(
|
||||
{
|
||||
"error": error_msg,
|
||||
"status": -100,
|
||||
"total": 0,
|
||||
"items": [],
|
||||
}
|
||||
)
|
||||
|
||||
def get(self, request: HttpRequest) -> JsonResponse:
|
||||
try:
|
||||
@ -22,9 +33,5 @@ class TagCoordApiView(View):
|
||||
return JsonResponse(data)
|
||||
except Exception:
|
||||
logger.error(traceback.format_exc())
|
||||
return {
|
||||
"error": "server error",
|
||||
"status": -100,
|
||||
"total": 0,
|
||||
"items": [],
|
||||
}
|
||||
error_msg = traceback.format_exc() if settings.DEBUG else "Server error"
|
||||
return self._error_response(error_msg)
|
||||
|
||||
@ -2,14 +2,12 @@
|
||||
{% load static %}
|
||||
{% load settings_tag %}
|
||||
{% block header_link %}
|
||||
<link rel="stylesheet"
|
||||
href="{% static 'street_pos/openLayers/theme/default/ol.css' %}?ver={% settings_value 'APP_VERSION' %}">
|
||||
|
||||
{# <link rel="stylesheet"#}
|
||||
{# href="{% static 'street_pos/openLayers/ol-ext/ol-ext.min.css' %}?ver={% settings_value 'APP_VERSION' %}">#}
|
||||
{##}
|
||||
{# <link rel="stylesheet"#}
|
||||
{# href="{% static 'street_pos/openLayers/ol-ext/ol-layer-theme.css' %}?ver={% settings_value 'APP_VERSION' %}">#}
|
||||
<link rel="stylesheet"
|
||||
href="{% static '/openLayers/theme/default/ol.css' %}?ver={% settings_value 'APP_VERSION' %}">
|
||||
<link rel="stylesheet"
|
||||
href="{% static '/openLayers/theme/map-widgets.css' %}?ver={% settings_value 'APP_VERSION' %}">
|
||||
<link rel="stylesheet" href="{% static '/main/main.css' %}?ver={% settings_value 'APP_VERSION' %}">
|
||||
{% endblock %}
|
||||
{% block content %}
|
||||
<section class="content">
|
||||
@ -38,8 +36,18 @@
|
||||
<div class="col-md-9">
|
||||
<div class="card mb-0">
|
||||
<div class="card-body table-responsive p-0" style="height: 85vh; padding-left: 0;">
|
||||
<div id="map" class="w-100 h-100">
|
||||
<div id="map" class="h-100 w-100">
|
||||
<button type="button" id="toStart" 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 id="LayerSwitcher">
|
||||
<div class="layers-btn-container">
|
||||
<div id="layers-btn"></div>
|
||||
</div>
|
||||
<div id="LayerSwitcherInner"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div> <!-- /.card-body -->
|
||||
</div> <!-- /.card -->
|
||||
@ -47,13 +55,144 @@
|
||||
</div><!-- /.container-fluid -->
|
||||
</div>
|
||||
</section>
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'street_pos/openLayers/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
{# <script src="{% static 'street_pos/openLayers/ol-ext/ol-ext.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>#}
|
||||
{% endblock %}
|
||||
{% block script_footer %}
|
||||
{% include 'street_pos/includes/map_script.html' with lat=map_center_lat lon=map_center_lon %}
|
||||
{% endblock %}
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script src="{% static '/openLayers/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/ol-ext/ol-ext.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/map/map-core.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/map/map-layer-switcher.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/map/map-marker-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
<script src="{% static '/openLayers/map/map-created-layer-manager.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||||
{% endblock %}
|
||||
{% block script_footer %}
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
// Инициализация карты
|
||||
const mapCore = new MapCore('map', {
|
||||
center: ['{{map_center_lon}}', '{{map_center_lat}}'],
|
||||
zoom: 12
|
||||
});
|
||||
|
||||
await mapCore.initialize();
|
||||
|
||||
// Инициализация переключателя слоев
|
||||
const LayerSwitcherInner = document.getElementById('LayerSwitcherInner')
|
||||
const layerSwitcher = new LayerSwitcher(mapCore, LayerSwitcherInner);
|
||||
|
||||
const workerLayer = new ol.layer.Vector({source: new ol.source.Vector()});
|
||||
workerLayer.set('title', 'Местоположение персонала')
|
||||
const workerManager = new MarkerManager(workerLayer, VlocationStyleFunction);
|
||||
|
||||
mapCore.addLayer(workerLayer, 'dynamic');
|
||||
|
||||
const scanLayer = new ol.layer.Tile({
|
||||
source: new ol.source.XYZ({
|
||||
url: '/media/map/orth/tiles/{z}/{x}/{y}.png?ver={% settings_value 'APP_VER' %}',
|
||||
}),
|
||||
extent: ol.proj.transformExtent(
|
||||
[
|
||||
parseFloat('{{ orth_minLon }}'),
|
||||
parseFloat('{{ orth_minLat }}'),
|
||||
parseFloat('{{ orth_maxLon }}'),
|
||||
parseFloat('{{ orth_maxLat }}')
|
||||
],
|
||||
'EPSG:4326', // Исходная проекция
|
||||
'EPSG:3857' // Целевая проекция
|
||||
)
|
||||
});
|
||||
|
||||
|
||||
// Кнопка возврата
|
||||
document.getElementById('toStart').addEventListener('click', () => {
|
||||
mapCore.map.getView().animate({
|
||||
center: ol.proj.fromLonLat(['{{lon}}', '{{lat}}']),
|
||||
zoom: 12
|
||||
});
|
||||
});
|
||||
|
||||
// Функция для обновления маркеров
|
||||
async function updateMarkers() {
|
||||
// Обновление работников
|
||||
const workersData = await fetch('{% url 'street_pos:tags_list_api' %}')
|
||||
.then(r => r.json());
|
||||
|
||||
const workersTableBody = document.querySelector('#workersTableBody')
|
||||
const workersCount = document.querySelector('#workersCount')
|
||||
workersCount.textContent = `( ${workersData.total} )`
|
||||
workersTableBody.innerHTML = ''
|
||||
|
||||
workersData.items.forEach(worker => {
|
||||
let tableRow = createWorkersTableRow(worker)
|
||||
workersTableBody.appendChild(tableRow)
|
||||
if (workerManager.markers[worker.id]) {
|
||||
workerManager.animateMarker(worker.id, [worker.lon, worker.lat]);
|
||||
workerManager.updateMarker(worker.id, [worker.lon, worker.lat], worker);
|
||||
} else {
|
||||
workerManager.addMarker(worker.id, [worker.lon, worker.lat], worker);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
await updateMarkers();
|
||||
setInterval(updateMarkers, 3000);
|
||||
|
||||
function createWorkersTableRow(worker) {
|
||||
const tr = document.createElement('tr')
|
||||
|
||||
const tdWorkerID = document.createElement('td')
|
||||
tdWorkerID.textContent = worker.name
|
||||
|
||||
// Переход по клику на координату
|
||||
const tdWorkerCoord = document.createElement('td')
|
||||
const showCoordButton = document.createElement('a')
|
||||
showCoordButton.className = 'worker-show-button'
|
||||
showCoordButton.style.cursor = 'pointer'
|
||||
showCoordButton.dataset.worker_id = worker.id
|
||||
showCoordButton.textContent = "Показать на карте"
|
||||
showCoordButton.addEventListener('click', (ev) => {
|
||||
const feature = workerManager.markers[ev.target.dataset.worker_id];
|
||||
const featureCoords = feature.getGeometry().getCoordinates();
|
||||
// Устанавливаем новый вид карты
|
||||
mapCore.map.getView().animate({
|
||||
center: featureCoords,
|
||||
zoom: 17,
|
||||
duration: 1000,
|
||||
});
|
||||
setTimeout(() => {
|
||||
showPopover(feature, featureCoords)
|
||||
}, 1001)
|
||||
});
|
||||
tdWorkerCoord.appendChild(showCoordButton)
|
||||
|
||||
switch (worker.condition) {
|
||||
case "ok":
|
||||
tdWorkerCoord.style.backgroundColor = ''
|
||||
break
|
||||
case "warning":
|
||||
tdWorkerCoord.style.backgroundColor = 'var(--warning)'
|
||||
break
|
||||
case "danger":
|
||||
tdWorkerCoord.style.backgroundColor = '#bebebe'
|
||||
break
|
||||
}
|
||||
|
||||
tr.appendChild(tdWorkerID)
|
||||
tr.appendChild(tdWorkerCoord)
|
||||
return tr
|
||||
}
|
||||
|
||||
function VlocationStyleFunction(feature, resolution) {
|
||||
return new ol.style.Style({
|
||||
image: new ol.style.Icon({
|
||||
src: '/static/img/worker.png',
|
||||
width: 25,
|
||||
height: 30
|
||||
})
|
||||
})
|
||||
}
|
||||
});
|
||||
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block form %}{% endblock %}
|
||||
|
||||
@ -0,0 +1,33 @@
|
||||
# Generated by Django 4.2.19 on 2025-03-31 07:48
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("workers", "0003_alter_worker_tag"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name="workshift",
|
||||
name="is_weekday",
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="workshift",
|
||||
name="shift_type",
|
||||
field=models.CharField(
|
||||
choices=[
|
||||
("regular", "Обычный график (5/2)"),
|
||||
("shift", "Сменный график (2/2, 1/3 и т.д.)"),
|
||||
("flexible", "Гибкий график"),
|
||||
("night", "Ночная смена"),
|
||||
("remote", "Удаленный режим"),
|
||||
],
|
||||
default="regular",
|
||||
help_text="Выберите тип рабочего графика",
|
||||
max_length=10,
|
||||
verbose_name="Тип графика",
|
||||
),
|
||||
),
|
||||
]
|
||||
39
static/gis/css/ol3.css
Normal file
@ -0,0 +1,39 @@
|
||||
.dj_map_wrapper {
|
||||
position: relative;
|
||||
float: left;
|
||||
}
|
||||
html[dir="rtl"] .dj_map_wrapper {
|
||||
float: right;
|
||||
}
|
||||
|
||||
.switch-type {
|
||||
background-repeat: no-repeat;
|
||||
cursor: pointer;
|
||||
top: 0.5em;
|
||||
width: 22px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.type-Point {
|
||||
background-image: url("../img/draw_point_off.svg");
|
||||
right: 5px;
|
||||
}
|
||||
.type-Point.type-active {
|
||||
background-image: url("../img/draw_point_on.svg");
|
||||
}
|
||||
|
||||
.type-LineString {
|
||||
background-image: url("../img/draw_line_off.svg");
|
||||
right: 30px;
|
||||
}
|
||||
.type-LineString.type-active {
|
||||
background-image: url("../img/draw_line_on.svg");
|
||||
}
|
||||
|
||||
.type-Polygon {
|
||||
background-image: url("../img/draw_polygon_off.svg");
|
||||
right: 55px;
|
||||
}
|
||||
.type-Polygon.type-active {
|
||||
background-image: url("../img/draw_polygon_on.svg");
|
||||
}
|
||||
1
static/gis/img/draw_line_off.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="22" height="20" viewBox="0 0 1000 915" xmlns="http://www.w3.org/2000/svg"><g><rect fill="#EDEDE8" x="20" y="20" width="960" height="875" rx="119" ry="119"/><path fill="#9F9F93" class="fil1" d="M139 0l722 0c38,0 73,16 98,41 25,25 41,60 41,98l0 637c0,38 -16,73 -41,98 -25,25 -60,41 -98,41l-722 0c-38,0 -73,-16 -98,-41 -25,-25 -41,-60 -41,-98l0 -637c0,-38 16,-73 41,-98 25,-25 60,-41 98,-41zm722 40l-722 0c-27,0 -52,11 -70,29 -18,18 -29,43 -29,70l0 637c0,27 11,52 29,70 18,18 43,29 70,29l722 0c27,0 52,-11 70,-29 18,-18 29,-43 29,-70l0 -637c0,-27 -11,-52 -29,-70 -18,-18 -43,-29 -70,-29z"/><polygon fill="#ABABA7" class="fil2" points="159,536 378,194 848,368 761,713 738,707 820,383 387,222 179,548 "/><circle fill="#000000" cx="383" cy="208" r="49"/><circle fill="#000000" cx="169" cy="542" r="49"/><circle fill="#000000" cx="834" cy="375" r="49"/><circle fill="#000000" cx="749" cy="710" r="49"/></g></svg>
|
||||
|
After Width: | Height: | Size: 918 B |
1
static/gis/img/draw_line_on.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="22" height="20" viewBox="0 0 1000 915" xmlns="http://www.w3.org/2000/svg"><g><rect fill="#F3C022" x="20" y="20" width="960" height="875" rx="119" ry="119"/><path fill="#9F9F93" d="M139 0l722 0c38,0 73,16 98,41 25,25 41,60 41,98l0 637c0,38 -16,73 -41,98 -25,25 -60,41 -98,41l-722 0c-38,0 -73,-16 -98,-41 -25,-25 -41,-60 -41,-98l0 -637c0,-38 16,-73 41,-98 25,-25 60,-41 98,-41zm722 40l-722 0c-27,0 -52,11 -70,29 -18,18 -29,43 -29,70l0 637c0,27 11,52 29,70 18,18 43,29 70,29l722 0c27,0 52,-11 70,-29 18,-18 29,-43 29,-70l0 -637c0,-27 -11,-52 -29,-70 -18,-18 -43,-29 -70,-29z"/><polygon fill="#B08A15" points="159,536 378,194 848,368 761,713 738,707 820,383 387,222 179,548 "/><circle fill="#000000" cx="383" cy="208" r="49"/><circle fill="#000000" cx="169" cy="542" r="49"/><circle fill="#000000" cx="834" cy="375" r="49"/><circle fill="#000000" cx="749" cy="710" r="49"/></g></svg>
|
||||
|
After Width: | Height: | Size: 892 B |
1
static/gis/img/draw_point_off.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="22" height="20" viewBox="0 0 1000 915" xmlns="http://www.w3.org/2000/svg"><g><rect fill="#EDEDE8" x="20" y="20" width="960" height="875" rx="119" ry="119"/><path fill="#9F9F93" d="M139 0l722 0c38,0 73,16 98,41 25,25 41,60 41,98l0 637c0,38 -16,73 -41,98 -25,25 -60,41 -98,41l-722 0c-38,0 -73,-16 -98,-41 -25,-25 -41,-60 -41,-98l0 -637c0,-38 16,-73 41,-98 25,-25 60,-41 98,-41zm722 40l-722 0c-27,0 -52,11 -70,29 -18,18 -29,43 -29,70l0 637c0,27 11,52 29,70 18,18 43,29 70,29l722 0c27,0 52,-11 70,-29 18,-18 29,-43 29,-70l0 -637c0,-27 -11,-52 -29,-70 -18,-18 -43,-29 -70,-29z"/><path fill="#000000" d="M573 269l114 114 -289 288 -114 -114 289 -288zm200 -28l-51 -50c-19,-20 -51,-20 -71,0l-49 48 114 114 57 -57c15,-15 15,-39 0,-55zm-548 476c-2,10 6,18 15,16l127 -31 -113 -114 -29 129z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 803 B |
1
static/gis/img/draw_point_on.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="22" height="20" viewBox="0 0 1000 915" xmlns="http://www.w3.org/2000/svg"><g><rect fill="#F3C022" x="20" y="20" width="960" height="875" rx="119" ry="119"/><path fill="#9F9F93" d="M139 0l722 0c38,0 73,16 98,41 25,25 41,60 41,98l0 637c0,38 -16,73 -41,98 -25,25 -60,41 -98,41l-722 0c-38,0 -73,-16 -98,-41 -25,-25 -41,-60 -41,-98l0 -637c0,-38 16,-73 41,-98 25,-25 60,-41 98,-41zm722 40l-722 0c-27,0 -52,11 -70,29 -18,18 -29,43 -29,70l0 637c0,27 11,52 29,70 18,18 43,29 70,29l722 0c27,0 52,-11 70,-29 18,-18 29,-43 29,-70l0 -637c0,-27 -11,-52 -29,-70 -18,-18 -43,-29 -70,-29z"/><path fill="#000000" d="M573 269l114 114 -289 288 -114 -114 289 -288zm200 -28l-51 -50c-19,-20 -51,-20 -71,0l-49 48 114 114 57 -57c15,-15 15,-39 0,-55zm-548 476c-2,10 6,18 15,16l127 -31 -113 -114 -29 129z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 803 B |
1
static/gis/img/draw_polygon_off.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="22" height="20" viewBox="0 0 1000 915" xmlns="http://www.w3.org/2000/svg"><g><rect fill="#EDEDE8" x="20" y="20" width="960" height="875" rx="119" ry="119"/><path fill="#9F9F93" d="M139 0l722 0c38,0 73,16 98,41 25,25 41,60 41,98l0 637c0,38 -16,73 -41,98 -25,25 -60,41 -98,41l-722 0c-38,0 -73,-16 -98,-41 -25,-25 -41,-60 -41,-98l0 -637c0,-38 16,-73 41,-98 25,-25 60,-41 98,-41zm722 40l-722 0c-27,0 -52,11 -70,29 -18,18 -29,43 -29,70l0 637c0,27 11,52 29,70 18,18 43,29 70,29l722 0c27,0 52,-11 70,-29 18,-18 29,-43 29,-70l0 -637c0,-27 -11,-52 -29,-70 -18,-18 -43,-29 -70,-29z"/><polygon fill="#F1DFAC" points="169,542 749,710 834,375 383,208 "/><path fill="ABABA7" d="M188 535l553 160 79 -312 -433 -161 -199 313zm558 186l-595 -172 227 -355 470 174 -90 356 -12 -3z"/><circle fill="#000000" cx="383" cy="208" r="49"/><circle fill="#000000" cx="169" cy="542" r="49"/><circle fill="#000000" cx="834" cy="375" r="49"/><circle fill="#000000" cx="749" cy="710" r="49"/></g></svg>
|
||||
|
After Width: | Height: | Size: 981 B |
1
static/gis/img/draw_polygon_on.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg width="22" height="20" viewBox="0 0 1000 915" xmlns="http://www.w3.org/2000/svg"><g><rect fill="#F3C022" x="20" y="20" width="960" height="875" rx="119" ry="119"/><path fill="#9F9F93" d="M139 0l722 0c38,0 73,16 98,41 25,25 41,60 41,98l0 637c0,38 -16,73 -41,98 -25,25 -60,41 -98,41l-722 0c-38,0 -73,-16 -98,-41 -25,-25 -41,-60 -41,-98l0 -637c0,-38 16,-73 41,-98 25,-25 60,-41 98,-41zm722 40l-722 0c-27,0 -52,11 -70,29 -18,18 -29,43 -29,70l0 637c0,27 11,52 29,70 18,18 43,29 70,29l722 0c27,0 52,-11 70,-29 18,-18 29,-43 29,-70l0 -637c0,-27 -11,-52 -29,-70 -18,-18 -43,-29 -70,-29z"/><polygon fill="#F7D56E" points="169,542 749,710 834,375 383,208 "/><path fill="#B08A15" d="M188 535l553 160 79 -312 -433 -161 -199 313zm558 186l-595 -172 227 -355 470 174 -90 356 -12 -3z"/><circle fill="#000000" cx="383" cy="208" r="49"/><circle fill="#000000" cx="169" cy="542" r="49"/><circle fill="#000000" cx="834" cy="375" r="49"/><circle fill="#000000" cx="749" cy="710" r="49"/></g></svg>
|
||||
|
After Width: | Height: | Size: 982 B |
238
static/gis/js/OLMapWidget.js
Normal file
@ -0,0 +1,238 @@
|
||||
/* global ol */
|
||||
'use strict';
|
||||
class GeometryTypeControl extends ol.control.Control {
|
||||
// Map control to switch type when geometry type is unknown
|
||||
constructor(opt_options) {
|
||||
const options = opt_options || {};
|
||||
|
||||
const element = document.createElement('div');
|
||||
element.className = 'switch-type type-' + options.type + ' ol-control ol-unselectable';
|
||||
if (options.active) {
|
||||
element.classList.add("type-active");
|
||||
}
|
||||
|
||||
super({
|
||||
element: element,
|
||||
target: options.target
|
||||
});
|
||||
const self = this;
|
||||
const switchType = function(e) {
|
||||
e.preventDefault();
|
||||
if (options.widget.currentGeometryType !== self) {
|
||||
options.widget.map.removeInteraction(options.widget.interactions.draw);
|
||||
options.widget.interactions.draw = new ol.interaction.Draw({
|
||||
features: options.widget.featureCollection,
|
||||
type: options.type
|
||||
});
|
||||
options.widget.map.addInteraction(options.widget.interactions.draw);
|
||||
options.widget.currentGeometryType.element.classList.remove('type-active');
|
||||
options.widget.currentGeometryType = self;
|
||||
element.classList.add("type-active");
|
||||
}
|
||||
};
|
||||
|
||||
element.addEventListener('click', switchType, false);
|
||||
element.addEventListener('touchstart', switchType, false);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: allow deleting individual features (#8972)
|
||||
class MapWidget {
|
||||
constructor(options) {
|
||||
this.map = null;
|
||||
this.interactions = {draw: null, modify: null};
|
||||
this.typeChoices = false;
|
||||
this.ready = false;
|
||||
|
||||
// Default options
|
||||
this.options = {
|
||||
default_lat: 0,
|
||||
default_lon: 0,
|
||||
default_zoom: 12,
|
||||
is_collection: options.geom_name.includes('Multi') || options.geom_name.includes('Collection')
|
||||
};
|
||||
|
||||
// Altering using user-provided options
|
||||
for (const property in options) {
|
||||
if (options.hasOwnProperty(property)) {
|
||||
this.options[property] = options[property];
|
||||
}
|
||||
}
|
||||
if (!options.base_layer) {
|
||||
this.options.base_layer = new ol.layer.Tile({source: new ol.source.OSM()});
|
||||
}
|
||||
|
||||
// RemovedInDjango51Warning: when the deprecation ends, remove setting
|
||||
// width/height (3 lines below).
|
||||
const mapContainer = document.getElementById(this.options.map_id);
|
||||
mapContainer.style.width = `${mapContainer.dataset.width}px`;
|
||||
mapContainer.style.height = `${mapContainer.dataset.height}px`;
|
||||
this.map = this.createMap();
|
||||
this.featureCollection = new ol.Collection();
|
||||
this.featureOverlay = new ol.layer.Vector({
|
||||
map: this.map,
|
||||
source: new ol.source.Vector({
|
||||
features: this.featureCollection,
|
||||
useSpatialIndex: false // improve performance
|
||||
}),
|
||||
updateWhileAnimating: true, // optional, for instant visual feedback
|
||||
updateWhileInteracting: true // optional, for instant visual feedback
|
||||
});
|
||||
|
||||
// Populate and set handlers for the feature container
|
||||
const self = this;
|
||||
this.featureCollection.on('add', function(event) {
|
||||
const feature = event.element;
|
||||
feature.on('change', function() {
|
||||
self.serializeFeatures();
|
||||
});
|
||||
if (self.ready) {
|
||||
self.serializeFeatures();
|
||||
if (!self.options.is_collection) {
|
||||
self.disableDrawing(); // Only allow one feature at a time
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const initial_value = document.getElementById(this.options.id).value;
|
||||
if (initial_value) {
|
||||
const jsonFormat = new ol.format.GeoJSON();
|
||||
const features = jsonFormat.readFeatures('{"type": "Feature", "geometry": ' + initial_value + '}');
|
||||
const extent = ol.extent.createEmpty();
|
||||
features.forEach(function(feature) {
|
||||
this.featureOverlay.getSource().addFeature(feature);
|
||||
ol.extent.extend(extent, feature.getGeometry().getExtent());
|
||||
}, this);
|
||||
// Center/zoom the map
|
||||
this.map.getView().fit(extent, {minResolution: 1});
|
||||
} else {
|
||||
this.map.getView().setCenter(this.defaultCenter());
|
||||
}
|
||||
this.createInteractions();
|
||||
if (initial_value && !this.options.is_collection) {
|
||||
this.disableDrawing();
|
||||
}
|
||||
const clearNode = document.getElementById(this.map.getTarget()).nextElementSibling;
|
||||
if (clearNode.classList.contains('clear_features')) {
|
||||
clearNode.querySelector('a').addEventListener('click', (ev) => {
|
||||
ev.preventDefault();
|
||||
self.clearFeatures();
|
||||
});
|
||||
}
|
||||
this.ready = true;
|
||||
}
|
||||
|
||||
createMap() {
|
||||
return new ol.Map({
|
||||
target: this.options.map_id,
|
||||
layers: [this.options.base_layer],
|
||||
view: new ol.View({
|
||||
zoom: this.options.default_zoom
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
createInteractions() {
|
||||
// Initialize the modify interaction
|
||||
this.interactions.modify = new ol.interaction.Modify({
|
||||
features: this.featureCollection,
|
||||
deleteCondition: function(event) {
|
||||
return ol.events.condition.shiftKeyOnly(event) &&
|
||||
ol.events.condition.singleClick(event);
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize the draw interaction
|
||||
let geomType = this.options.geom_name;
|
||||
if (geomType === "Geometry" || geomType === "GeometryCollection") {
|
||||
// Default to Point, but create icons to switch type
|
||||
geomType = "Point";
|
||||
this.currentGeometryType = new GeometryTypeControl({widget: this, type: "Point", active: true});
|
||||
this.map.addControl(this.currentGeometryType);
|
||||
this.map.addControl(new GeometryTypeControl({widget: this, type: "LineString", active: false}));
|
||||
this.map.addControl(new GeometryTypeControl({widget: this, type: "Polygon", active: false}));
|
||||
this.typeChoices = true;
|
||||
}
|
||||
this.interactions.draw = new ol.interaction.Draw({
|
||||
features: this.featureCollection,
|
||||
type: geomType
|
||||
});
|
||||
|
||||
this.map.addInteraction(this.interactions.draw);
|
||||
this.map.addInteraction(this.interactions.modify);
|
||||
}
|
||||
|
||||
defaultCenter() {
|
||||
const center = [this.options.default_lon, this.options.default_lat];
|
||||
if (this.options.map_srid) {
|
||||
return ol.proj.transform(center, 'EPSG:4326', this.map.getView().getProjection());
|
||||
}
|
||||
return center;
|
||||
}
|
||||
|
||||
enableDrawing() {
|
||||
this.interactions.draw.setActive(true);
|
||||
if (this.typeChoices) {
|
||||
// Show geometry type icons
|
||||
const divs = document.getElementsByClassName("switch-type");
|
||||
for (let i = 0; i !== divs.length; i++) {
|
||||
divs[i].style.visibility = "visible";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
disableDrawing() {
|
||||
if (this.interactions.draw) {
|
||||
this.interactions.draw.setActive(false);
|
||||
if (this.typeChoices) {
|
||||
// Hide geometry type icons
|
||||
const divs = document.getElementsByClassName("switch-type");
|
||||
for (let i = 0; i !== divs.length; i++) {
|
||||
divs[i].style.visibility = "hidden";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clearFeatures() {
|
||||
this.featureCollection.clear();
|
||||
// Empty textarea widget
|
||||
document.getElementById(this.options.id).value = '';
|
||||
this.enableDrawing();
|
||||
}
|
||||
|
||||
serializeFeatures() {
|
||||
// Three use cases: GeometryCollection, multigeometries, and single geometry
|
||||
let geometry = null;
|
||||
const features = this.featureOverlay.getSource().getFeatures();
|
||||
if (this.options.is_collection) {
|
||||
if (this.options.geom_name === "GeometryCollection") {
|
||||
const geometries = [];
|
||||
for (let i = 0; i < features.length; i++) {
|
||||
geometries.push(features[i].getGeometry());
|
||||
}
|
||||
geometry = new ol.geom.GeometryCollection(geometries);
|
||||
} else {
|
||||
geometry = features[0].getGeometry().clone();
|
||||
for (let j = 1; j < features.length; j++) {
|
||||
switch (geometry.getType()) {
|
||||
case "MultiPoint":
|
||||
geometry.appendPoint(features[j].getGeometry().getPoint(0));
|
||||
break;
|
||||
case "MultiLineString":
|
||||
geometry.appendLineString(features[j].getGeometry().getLineString(0));
|
||||
break;
|
||||
case "MultiPolygon":
|
||||
geometry.appendPolygon(features[j].getGeometry().getPolygon(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (features[0]) {
|
||||
geometry = features[0].getGeometry();
|
||||
}
|
||||
}
|
||||
const jsonFormat = new ol.format.GeoJSON();
|
||||
document.getElementById(this.options.id).value = jsonFormat.writeGeometry(geometry);
|
||||
}
|
||||
}
|
||||
BIN
static/img/worker.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
121
static/openLayers/layersStyles.js
Normal file
@ -0,0 +1,121 @@
|
||||
const getGTOMarkerText = function (feature) {
|
||||
const statemum = feature.get('garagenum')
|
||||
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],
|
||||
});
|
||||
};
|
||||
|
||||
const createGTOZoneNameTextStyle = function (feature, resolution) {
|
||||
const font = 'bold' + ' ' + '9px' + '/' + '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'),
|
||||
padding: [3, 3, 3, 3],
|
||||
});
|
||||
};
|
||||
|
||||
function GTOStyleFunction(feature, resolution) {
|
||||
return new ol.style.Style({
|
||||
image: new ol.style.Icon({
|
||||
src: feature.get('icon') ? feature.get('icon') : "/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 polygonBrownStyleFunction(feature, resolution) {
|
||||
return new ol.style.Style({
|
||||
stroke: new ol.style.Stroke({
|
||||
color: 'rgb(199,136,10)',
|
||||
width: 2,
|
||||
}),
|
||||
fill: new ol.style.Fill({
|
||||
color: 'rgba(199,136,10, 0.6)',
|
||||
}),
|
||||
text: createGTOZoneNameTextStyle(feature, resolution)
|
||||
});
|
||||
}
|
||||
|
Before Width: | Height: | Size: 457 B After Width: | Height: | Size: 457 B |
|
Before Width: | Height: | Size: 524 B After Width: | Height: | Size: 524 B |
|
Before Width: | Height: | Size: 516 B After Width: | Height: | Size: 516 B |