519 lines
22 KiB
HTML
519 lines
22 KiB
HTML
{% extends "default.html" %}
|
||
{% load static %}
|
||
{% load mysettings %}
|
||
|
||
{% block header_link %}
|
||
<link rel="stylesheet" href="{% static 'js/ol/theme/default/style.css' %}?ver={% settings_value 'APP_VER' %}">
|
||
<link rel="stylesheet" href="{% static 'js/ol/theme/default/ol.css' %}?ver={% settings_value 'APP_VER' %}">
|
||
<link rel="stylesheet" href="{% static 'js/ol/ol-ext/ol-ext.min.css' %}?ver={% settings_value 'APP_VER' %}">
|
||
<link rel="stylesheet" href="{% static 'js/ol/ol-ext/ol-layer-theme.css' %}?ver={% settings_value 'APP_VER' %}">
|
||
<link rel="stylesheet" href="{% static 'css/main_page.css' %}?ver={% settings_value 'APP_VER' %}">
|
||
<style>
|
||
.file-upload-label {
|
||
cursor: pointer;
|
||
border: 1px solid #ced4da;
|
||
padding: .375rem .75rem;
|
||
border-radius: .25rem;
|
||
font-weight: normal !important;
|
||
}
|
||
|
||
.ol-status.ol-unselectable.ol-control.ol-visible {
|
||
background-color: rgba(0, 0, 0, 0.2) !important
|
||
}
|
||
</style>
|
||
{% endblock %}
|
||
{% block content %}
|
||
<section class="content text-sm p-1">
|
||
<div class="card h-100">
|
||
<div class="card-header">
|
||
<h3 class="card-title">Создание слоя</h3>
|
||
</div>
|
||
|
||
<!-- /.card-header -->
|
||
<form enctype="multipart/form-data" method="post" class="card-body">
|
||
<div class="row h-100">
|
||
<div class="col-md-6 col-sm-12">
|
||
<div class="card">
|
||
<div class="card-header">
|
||
<h3 class="card-title">Общие данные</h3>
|
||
</div>
|
||
<!-- form start -->
|
||
<div class="card-body">
|
||
<div class="form-group">
|
||
<label for="name">Наименование</label>
|
||
{{ form.name }}
|
||
</div>
|
||
<div class="form-group">
|
||
<label for="exampleInputFile">Файл</label>
|
||
<div class="input-group d-flex flex-column">
|
||
<label for="id_layer_file_input" class="file-upload-label">Выберите файл с
|
||
расширением
|
||
.kml, .json, .dxf</label>
|
||
<span>Сейчас выбран: <span id="file_path"
|
||
style="cursor: auto; color: var(--primary);"></span></span>
|
||
<input type="file" name="layer_file_input"
|
||
class="form-control"
|
||
autofocus=""
|
||
id="id_layer_file_input" style="visibility:hidden; display: none"
|
||
accept=".kml, .json, .dxf">
|
||
{{ form.file.as_hidden }}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="card-header">
|
||
<h3 class="card-title">Стиль слоя</h3>
|
||
</div>
|
||
<!-- form start -->
|
||
<div class="card-body">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="col-md-6 col-sm-12">
|
||
<div class="card h-100">
|
||
<div class="card-header">
|
||
<h3 class="card-title">Предпросмотр</h3>
|
||
</div>
|
||
<!-- form start -->
|
||
<div class="card-body p-0">
|
||
<div id="map"></div>
|
||
</div>
|
||
<div class="card-footer d-flex" style="gap: 30px">
|
||
<button id="exportGeoJSON" class="btn btn-info">Экспортировать GeoJSON</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</form>
|
||
<div class="card-footer">
|
||
<button type="submit" class="btn btn-primary" id="saveButton">Сохранить слой</button>
|
||
{% if layer %}
|
||
<a href="{% url 'layer_delete' layer.id %}" class="btn btn-danger float-right">Удалить слой</a>
|
||
{% endif %}
|
||
</div>
|
||
<!-- /.card-body -->
|
||
</div>
|
||
</section>
|
||
{% endblock %}
|
||
|
||
{% block script_footer %}
|
||
<script src="{% static 'js/ol/lib/OpenLayers.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
<script src="{% static 'js/ol/ol-ext/ol-ext.min.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
<script src="{% static 'js/ol/dxf-parser.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
|
||
<script src="{% static 'js/ol/layersStyles.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
<script src="{% static 'js/ol/mapCommonFuncs.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
<script src="{% static 'js/ol/timeSliderFuncs.js' %}?ver={% settings_value 'APP_VER' %}"></script>
|
||
<script>
|
||
const filePath = document.getElementById("file_path");
|
||
const fileField = document.getElementById("id_layer_file_input");
|
||
|
||
fileField.addEventListener("change", (ev) => {
|
||
const file = fileField.files[0]; // Получаем выбранный файл
|
||
if (file) {
|
||
filePath.textContent = file.name; // Устанавливаем имя файла как текст ссылки
|
||
}
|
||
});
|
||
|
||
</script>
|
||
|
||
<script>
|
||
let centerLat = parseFloat('{{lat}}')
|
||
let centerLon = parseFloat('{{lon}}')
|
||
let transformInteraction = {}
|
||
let translateInteraction = {}
|
||
let i = 0
|
||
const scanLayerExists = Boolean(parseInt('{{ scan_layer_enable }}'))
|
||
|
||
layers = [
|
||
new ol.layer.Tile({
|
||
source: new ol.source.OSM()
|
||
}),
|
||
]
|
||
if (scanLayerExists) {
|
||
scanLayer = new ol.layer.Tile({
|
||
source: new ol.source.XYZ({
|
||
url: '/media/map/orth/tiles/{z}/{x}/{y}.png',
|
||
}),
|
||
extent: ol.proj.transformExtent(
|
||
[
|
||
parseFloat('87.889212480'),
|
||
parseFloat('53.633875446'),
|
||
parseFloat('87.965792495'),
|
||
parseFloat('53.713365769')
|
||
],
|
||
'EPSG:4326', // Исходная проекция
|
||
'EPSG:3857' // Целевая проекция
|
||
)
|
||
});
|
||
scanLayer.set('name', 'Ортофотоплан')
|
||
layers.push(scanLayer)
|
||
}
|
||
const iconFeature = new ol.Feature({
|
||
geometry: new ol.geom.Point(ol.proj.fromLonLat([centerLon, centerLat])),
|
||
name: 'Null Island',
|
||
population: 4000,
|
||
rainfall: 500,
|
||
});
|
||
|
||
const iconStyle = new ol.style.Style({
|
||
image: new ol.style.Icon({
|
||
anchor: [0.5, 46],
|
||
anchorXUnits: 'fraction',
|
||
anchorYUnits: 'pixels',
|
||
src: '/static/img/earthquake.png',
|
||
width: 20,
|
||
height: 20,
|
||
}),
|
||
});
|
||
|
||
iconFeature.setStyle(iconStyle);
|
||
|
||
const exampleSource = new ol.source.Vector({
|
||
features: [iconFeature],
|
||
});
|
||
|
||
const exampleLayer = new ol.layer.Vector({
|
||
source: exampleSource,
|
||
});
|
||
layers.push(exampleLayer)
|
||
const map = new ol.Map({
|
||
target: 'map',
|
||
layers: layers,
|
||
view: new ol.View({
|
||
center: ol.proj.fromLonLat([centerLon, centerLat]), // Центр карты
|
||
zoom: 12,
|
||
})
|
||
});
|
||
translateInteraction = new ol.interaction.Translate({});
|
||
map.addInteraction(translateInteraction);
|
||
|
||
// Добавляем возможность масштабирования и перемещения с помощью маркеров
|
||
transformInteraction = new ol.interaction.Transform({
|
||
addCondition: ol.events.condition.shiftKeyOnly,
|
||
});
|
||
map.addInteraction(transformInteraction);
|
||
let vectorLayer;
|
||
|
||
// const ctrl = new ol.control.Status();
|
||
// map.addControl(ctrl);
|
||
// // Show information on each frame
|
||
// map.on('postrender', function (e) {
|
||
// console.log(ol.coordinate)
|
||
// // console.log(e)
|
||
// var c = map.getView().getCenter();
|
||
// ctrl.status({
|
||
// center: [Math.round(c[0]), Math.round(c[1])],
|
||
// lonlat: ol.coordinate.toStringXY(ol.proj.toLonLat(c), 7),
|
||
// zoom: map.getView().getZoom(),
|
||
// resolution: map.getView().getResolution().toFixed(4),
|
||
// angle: Math.round(map.getView().getRotation() * 180 / Math.PI * 100) / 100,
|
||
// size: map.getSize(),
|
||
// animate: e.frameState.animate
|
||
// });
|
||
// });
|
||
|
||
document.getElementById('id_layer_file_input').addEventListener('change', function (event) {
|
||
const file = event.target.files[0];
|
||
if (file) {
|
||
const reader = new FileReader();
|
||
reader.onload = function (e) {
|
||
const fileExtension = file.name.split('.').pop().toLowerCase();
|
||
if (fileExtension === 'dxf') {
|
||
const parser = new DxfParser();
|
||
try {
|
||
const dxf = parser.parseSync(e.target.result);
|
||
const geojson = dxfToGeoJSON(dxf);
|
||
clearVectorLayer();
|
||
addGeoJSONToMap(geojson);
|
||
} catch (error) {
|
||
console.error('DXF Parsing Error:', error);
|
||
}
|
||
} else if (fileExtension === 'kml') {
|
||
const kml = e.target.result;
|
||
clearVectorLayer();
|
||
addKMLToMap(kml);
|
||
}
|
||
};
|
||
reader.readAsText(file);
|
||
}
|
||
});
|
||
document.getElementById('exportGeoJSON').addEventListener('click', function () {
|
||
if (vectorLayer) {
|
||
const features = vectorLayer.getSource().getFeatures();
|
||
const geojson = new ol.format.GeoJSON().writeFeatures(features, {
|
||
featureProjection: 'EPSG:3857'
|
||
});
|
||
downloadGeoJSON(geojson);
|
||
}
|
||
});
|
||
|
||
const createDXFStyle = function (feature, resolution) {
|
||
return new ol.style.Style({
|
||
stroke: new ol.style.Stroke({
|
||
color: feature.get("color"),
|
||
width: 1,
|
||
}),
|
||
});
|
||
};
|
||
|
||
function getCoordinates(entity) {
|
||
if (entity.type === 'LINE') {
|
||
return [[entity.vertices[0].x, entity.vertices[0].y], [entity.vertices[1].x, entity.vertices[1].y]];
|
||
}
|
||
if (entity.type === 'LWPOLYLINE' || entity.type === 'POLYLINE') {
|
||
return entity.vertices.map(v => [v.x, v.y]);
|
||
}
|
||
if (entity.type === 'CIRCLE') {
|
||
return [[entity.center.x, entity.center.y]];
|
||
}
|
||
if (entity.type === 'ARC') {
|
||
return arcToLine(entity);
|
||
}
|
||
if (entity.type === 'POINT') {
|
||
return [[entity.position.x, entity.position.y]];
|
||
}
|
||
if (entity.type === 'SPLINE') {
|
||
return entity.controlPoints.map(v => [v.x, v.y]);
|
||
}
|
||
if (entity.type === "INSERT") {
|
||
{#const type = #}
|
||
console.log(entity)
|
||
}
|
||
return [];
|
||
}
|
||
|
||
function normalizeCoordinates(entities, dxfHeader) {
|
||
let minX = dxfHeader.$EXTMIN.x;
|
||
let minY = dxfHeader.$EXTMIN.y;
|
||
return entities.map(entity => {
|
||
const coords = getCoordinates(entity).map(([x, y]) => {
|
||
const normalizedX = x - minX;
|
||
const normalizedY = y - minY;
|
||
return convertToLonLat([normalizedX, normalizedY]);
|
||
});
|
||
return {...entity, normalizedCoords: coords};
|
||
});
|
||
}
|
||
|
||
function dxfToGeoJSON(dxf) {
|
||
console.log(dxf);
|
||
const normalizedEntities = normalizeCoordinates(dxf.entities, dxf.header);
|
||
const features = normalizedEntities.map(entity => {
|
||
if (entity.type === 'LINE') {
|
||
return createFeature('LineString', entity.normalizedCoords, {color: getColorByColorTable(entity.colorIndex)});
|
||
} else if (entity.type === 'LWPOLYLINE' || entity.type === 'POLYLINE') {
|
||
const coords = entity.normalizedCoords;
|
||
return createFeature(entity.closed ? 'Polygon' : 'LineString', entity.closed ? [coords] : coords,
|
||
{color: getColorByColorTable(entity.colorIndex)});
|
||
} else if (entity.type === 'CIRCLE') {
|
||
return createFeature('Point', entity.normalizedCoords[0], {
|
||
radius: entity.radius,
|
||
color: getColorByColorTable(entity.colorIndex)
|
||
});
|
||
} else if (entity.type === 'ARC') {
|
||
return createFeature('LineString', entity.normalizedCoords, {color: getColorByColorTable(entity.colorIndex)});
|
||
} else if (entity.type === 'POINT') {
|
||
return createFeature('Point', entity.normalizedCoords[0], {color: getColorByColorTable(entity.colorIndex)});
|
||
} else if (entity.type === 'SPLINE') {
|
||
return createFeature('LineString', entity.normalizedCoords, {color: getColorByColorTable(entity.colorIndex)});
|
||
}
|
||
return null;
|
||
}).filter(f => f !== null);
|
||
return {type: 'FeatureCollection', features: features};
|
||
}
|
||
|
||
function createFeature(type, coordinates, properties) {
|
||
i++
|
||
return {
|
||
type: 'Feature',
|
||
geometry: {type, coordinates},
|
||
properties
|
||
};
|
||
}
|
||
|
||
function arcToLine(arc) {
|
||
const coords = [];
|
||
const steps = 32;
|
||
const startAngle = (arc.startAngle * Math.PI) / 180;
|
||
const endAngle = (arc.endAngle * Math.PI) / 180;
|
||
const angleStep = (endAngle - startAngle) / steps;
|
||
for (let i = 0; i <= steps; i++) {
|
||
const angle = startAngle + i * angleStep;
|
||
coords.push([
|
||
arc.center.x + arc.radius * Math.cos(angle),
|
||
arc.center.y + arc.radius * Math.sin(angle)
|
||
]);
|
||
}
|
||
return coords;
|
||
}
|
||
|
||
function addKMLToMap(kml) {
|
||
if (vectorLayer) {
|
||
map.removeLayer(vectorLayer);
|
||
}
|
||
const vectorSource = new ol.source.Vector({
|
||
features: new ol.format.KML().readFeatures(kml, {
|
||
featureProjection: 'EPSG:3857'
|
||
})
|
||
});
|
||
vectorLayer = new ol.layer.Vector({
|
||
source: vectorSource,
|
||
style: new ol.style.Style({
|
||
stroke: new ol.style.Stroke({
|
||
color: 'red',
|
||
width: 2
|
||
}),
|
||
image: new ol.style.Circle({
|
||
radius: 5,
|
||
fill: new ol.style.Fill({color: 'blue'})
|
||
})
|
||
})
|
||
});
|
||
map.addLayer(vectorLayer);
|
||
|
||
// Настройка transformInteraction для редактирования
|
||
const features = vectorSource.getFeatures();
|
||
const group = new ol.Collection(features);
|
||
transformInteraction.setSelection(group);
|
||
|
||
// Обновляем выделение при перемещении мыши
|
||
map.on('pointermove', () => {
|
||
transformInteraction.setSelection(group);
|
||
});
|
||
|
||
const extent = vectorSource.getExtent();
|
||
if (!ol.extent.isEmpty(extent)) {
|
||
map.getView().fit(extent, {padding: [20, 20, 20, 20]});
|
||
} else {
|
||
console.warn('Слой не содержит геометрических объектов.');
|
||
}
|
||
}
|
||
|
||
function addGeoJSONToMap(geojson) {
|
||
if (vectorLayer) {
|
||
map.removeLayer(vectorLayer);
|
||
}
|
||
const vectorSource = new ol.source.Vector({
|
||
features: new ol.format.GeoJSON().readFeatures(geojson, {
|
||
featureProjection: 'EPSG:3857'
|
||
})
|
||
});
|
||
vectorLayer = new ol.layer.Vector({
|
||
source: vectorSource,
|
||
style: createDXFStyle
|
||
});
|
||
map.addLayer(vectorLayer);
|
||
|
||
// Настройка transformInteraction для редактирования
|
||
const features = vectorSource.getFeatures();
|
||
const group = new ol.Collection(features);
|
||
transformInteraction.setSelection(group);
|
||
|
||
// Обновляем выделение при перемещении мыши
|
||
map.on('pointermove', () => {
|
||
transformInteraction.setSelection(group);
|
||
});
|
||
|
||
const extent = vectorSource.getExtent();
|
||
if (!ol.extent.isEmpty(extent)) {
|
||
map.getView().fit(extent, {padding: [20, 20, 20, 20]});
|
||
} else {
|
||
console.warn('Слой не содержит геометрических объектов.');
|
||
}
|
||
}
|
||
|
||
function convertToLonLat([x, y]) {
|
||
|
||
const kx = 1.676;
|
||
const ky = 1.001;
|
||
|
||
let res = ol.proj.transform([x, y], 'EPSG:3857', 'EPSG:4326')
|
||
res[0] = kx * res[0] + 87.915936 // ДОЛГОТА
|
||
res[1] = ky * res[1] + 53.688360 // ШИРОТА
|
||
return res;
|
||
}
|
||
|
||
function downloadGeoJSON(geojson) {
|
||
const blob = new Blob([geojson], {type: 'application/json'});
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = 'export.geojson';
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
}
|
||
|
||
document.getElementById('saveButton').addEventListener('click', function () {
|
||
// TODO валидация формы. Вывод ошибок
|
||
if (vectorLayer) {
|
||
const features = vectorLayer.getSource().getFeatures();
|
||
const geojson = new ol.format.GeoJSON().writeFeatures(features, {
|
||
featureProjection: 'EPSG:3857'
|
||
});
|
||
const name = document.querySelector("#id_name")
|
||
|
||
const formData = new FormData();
|
||
formData.append('file', new Blob([geojson], {type: 'application/json'}), 'export.geojson');
|
||
formData.append('name', name.value)
|
||
|
||
// Отправляем данные на сервер
|
||
fetch(window.location.href, {
|
||
method: 'POST',
|
||
body: formData,
|
||
headers: {
|
||
'X-CSRFToken': '{{ csrf_token }}' // Добавляем CSRF-токен для защиты
|
||
}
|
||
}).then(response => {
|
||
if (response.ok) {
|
||
window.location.href = '/main/'
|
||
} else {
|
||
console.error('Ошибка при сохранении файла.');
|
||
}
|
||
}).catch(error => {
|
||
console.error('Ошибка:', error);
|
||
});
|
||
} else {
|
||
console.error('Нет данных для сохранения.');
|
||
}
|
||
});
|
||
|
||
function clearVectorLayer() {
|
||
if (vectorLayer) {
|
||
// Удаляем векторный слой с карты
|
||
map.removeLayer(vectorLayer);
|
||
vectorLayer = null;
|
||
}
|
||
const emptyGroup = new ol.Collection();
|
||
transformInteraction.setSelection(emptyGroup)
|
||
}
|
||
|
||
document.addEventListener('DOMContentLoaded', function () {
|
||
const fileInput = document.getElementById('id_file');
|
||
if (fileInput && fileInput.value) {
|
||
const fileUrl = "/media/" + fileInput.value; // URL файла
|
||
const fileExtension = fileUrl.split('.').pop().toLowerCase();
|
||
|
||
if (fileExtension === 'geojson' || fileExtension === 'json') {
|
||
fetch(fileUrl)
|
||
.then(response => response.json())
|
||
.then(geojson => {
|
||
clearVectorLayer();
|
||
addGeoJSONToMap(geojson);
|
||
})
|
||
.catch(error => console.error('Ошибка загрузки GeoJSON:', error));
|
||
} else if (fileExtension === 'kml') {
|
||
fetch(fileUrl)
|
||
.then(response => response.text())
|
||
.then(kml => {
|
||
clearVectorLayer();
|
||
addKMLToMap(kml);
|
||
})
|
||
.catch(error => console.error('Ошибка загрузки KML:', error));
|
||
}
|
||
}
|
||
});
|
||
</script>
|
||
{% endblock %} |