test/apps/main/templates/create_layer.html

590 lines
26 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{% 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-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="mb-2">Создание слоя</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="{% url 'mainindex' %}">Главная</a>
</li>
<li class="breadcrumb-item active">Создание слоя</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<section class="content text-sm p-1">
<div class="card" style="height: 90%;">
<!-- /.card-header -->
<form enctype="multipart/form-data" method="post" class="card-body">
<div class="row h-100">
<div class="col-md-4 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, .geojson, .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, .geojson, .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-8 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="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.15.0/proj4-src.js"></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',
});
function getCoordsByFeature(feature, resoluiton) {
const coords = feature.getGeometry().getCoordinates()
const coordsIn4326 = ol.proj.transform(coords, 'EPSG:3857', 'EPSG:4326');
return {
lat: coordsIn4326[0],
lon: coordsIn4326[1],
formatted: `${coordsIn4326[0]} ${coordsIn4326[1]}`,
}
}
function iconStyle(feature, resolution) {
return 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,
}),
text: new ol.style.Text({
textAlign: 'center',
textBaseline: 'middle',
text: getCoordsByFeature(feature, resolution).formatted,
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 exampleSource = new ol.source.Vector({
features: [iconFeature],
});
// const exampleLayer = new ol.layer.Vector({
// source: exampleSource,
// style: iconStyle
// });
// 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,
translateFeature: false
});
map.addInteraction(transformInteraction);
let vectorLayer;
// Обработчик клика на карту
map.on('click', function (event) {
const features = map.getFeaturesAtPixel(event.pixel); // Получаем объекты в точке клика
console.log(getCoordsByFeature(features[0]).formatted)
});
// 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);
} else if (fileExtension === "json" || fileExtension === "geojson") {
const geojson = JSON.parse(e.target.result)
clearVectorLayer()
addGeoJSONToMap(geojson)
}
};
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,
}),
image: new ol.style.Circle({
radius: 10, // Размер точки
fill: new ol.style.Fill({
color: 'red', // Цвет заливки
}),
stroke: new ol.style.Stroke({
color: 'white', // Цвет обводки
width: 2, // Толщина обводки
}),
}),
});
};
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]);
}
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);
console.log(features)
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({extractStyles: false}).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]) {
proj4.defs(
"EPSG:28415",
"+proj=tmerc +lat_0=0 +lon_0=87 +k=1 +x_0=15500000 +y_0=0 +ellps=krass +towgs84=23.57,-140.95,-79.8,0,0.35,0.79,-0.22 +units=m +no_defs"
);
// Определение проекции WGS84 (EPSG:4326)
proj4.defs("EPSG:4326", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
// Преобразование координат
const transformedCoords = proj4("EPSG:28415", "EPSG:4326", [x, y]);
// Возвращаем результат (долгота, широта)
return [transformedCoords[0], transformedCoords[1]];
}
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');
if (!name.value) {
formData.append("name", fileField.files[0].name)
} else {
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 %}