test/apps/main/templates/create_layer.html

695 lines
31 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>
{% if not layer %}
<div class="form-group">
<div class="row">
<div class="col-6">
<label for="XOffsetField">Xпопр:</label>
<input type="number" name="XOffset" id="XOffsetField"
class="form-control"
min="0" value="0">
</div>
<div class="col-6">
<label for="YOffsetField">Yпопр:</label>
<input type="number" name="YOffset" id="YOffsetField"
class="form-control"
min="0" value="0">
</div>
</div>
</div>
{% endif %}
<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 id="style-editor-container" 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="{% static 'js/ol/layersStyles.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<script src="{% static 'js/ol/proj4js.js' %}?ver={% settings_value 'APP_VER' %}"></script>
<script>
function rgbToHex(rgb) {
var hexRegex = /^#[0-9A-Fa-f]{6}$/; // Регулярное выражение для HEX формата
var rgbRegex = /^rgb\(\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*\)$/;
var result, r, g, b, hex = "";
// Проверка, если строка уже в HEX формате
if (hexRegex.test(rgb)) {
return rgb; // Возвращаем как есть, если уже HEX
}
// Если строка не в HEX, проверяем на RGB
if ((result = rgbRegex.exec(rgb))) {
r = componentFromStr(result[1], result[2]);
g = componentFromStr(result[3], result[4]);
b = componentFromStr(result[5], result[6]);
// Преобразуем RGB в HEX
hex = "#" + (0x1000000 + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
return hex;
}
function componentFromStr(value, isPercentage) {
if (isPercentage) {
value = Math.round((parseInt(value) / 100) * 255);
} else {
value = parseInt(value);
}
return Math.min(255, Math.max(0, value)); // Ограничиваем значения от 0 до 255
}
</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 }}'))
let vectorSource = {}
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('{{ orth_minLon }}'),
parseFloat('{{ orth_minLat }}'),
parseFloat('{{ orth_maxLon }}'),
parseFloat('{{ orth_maxLat }}')
],
'EPSG:4326', // Исходная проекция
'EPSG:3857' // Целевая проекция
)
});
scanLayer.set('name', 'Ортофотоплан')
layers.push(scanLayer)
}
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]}`,
}
}
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;
// Дефолтные значения стиля
const DEFAULT_STYLE = {
"stroke-color": "#0000ff", // Синий цвет обводки
"stroke-width": 2, // Толщина обводки
};
// Функция для обновления стиля слоя
function updateLayerStyle() {
const form = document.getElementById("style-editor");
const inputs = form.querySelectorAll("input");
// Обновляем стиль для всех фич в слое
vectorSource.getFeatures().forEach((feature) => {
const currentStyle = feature.get("style") || {};
inputs.forEach((input) => {
const property = input.id;
const value = input.type === "number" ? parseFloat(input.value) : input.value;
currentStyle[property] = value;
});
// Устанавливаем обновленный стиль
feature.set("style", currentStyle);
});
// Обновляем слой
vectorLayer.changed();
}
function getLabelForProperty(property) {
switch (property) {
case "stroke-color":
return "Цвет линии:"
case "stroke-width":
return "Ширина линии:"
}
}
// Функция для создания формы на основе свойств стиля
function createStyleForm(feature) {
const style = feature.get("style") || DEFAULT_STYLE; // Используем стиль из фичи или по умолчанию
const container = document.getElementById("style-editor-container");
// Очищаем контейнер
container.innerHTML = "";
// Создаем форму
const form = document.createElement("form");
form.id = "style-editor";
// Список свойств стиля для отображения в форме
const styleProperties = Object.keys(DEFAULT_STYLE);
const row = document.createElement("div");
row.className = "row";
// Динамически создаем поля для каждого свойства стиля
styleProperties.forEach((property) => {
const col = document.createElement("div");
col.className = "col-6";
const label = document.createElement("label");
label.textContent = getLabelForProperty(property);
label.setAttribute("for", property);
let input;
if (property === "stroke-width") {
input = document.createElement("input");
input.type = "number";
input.id = property;
input.value = style[property] || DEFAULT_STYLE[property];
input.className = "form-control";
input.min = 1;
input.max = 10;
} else if (property === "stroke-color") {
input = document.createElement("input");
input.type = "color";
input.id = property;
input.value = rgbToHex(style[property]) || DEFAULT_STYLE[property];
input.className = "form-control";
}
col.appendChild(label);
col.appendChild(input);
row.appendChild(col);
});
form.appendChild(row)
// Добавляем форму в контейнер
container.appendChild(form);
// Добавляем обработчики событий для полей ввода
form.querySelectorAll("input").forEach((input) => {
input.addEventListener("input", updateLayerStyle);
});
}
// Функция для инициализации формы при загрузке
function initializeForm() {
const features = vectorSource.getFeatures();
// Если фичи уже есть, создаем форму для первой фичи
if (features.length > 0) {
const firstFeature = features[0];
const style = firstFeature.get("style") || DEFAULT_STYLE; // Используем стиль из фичи или по умолчанию
createStyleForm(firstFeature);
}
}
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);
}
});
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]) => {
// Возможно отображение от нулевых координат. Для этого нужно отнимать minX и minY
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,
{
style: {"stroke-color": getColorByColorTable(entity.colorIndex), "stroke-width": 1}
});
} else if (entity.type === 'LWPOLYLINE' || entity.type === 'POLYLINE') {
const coords = entity.normalizedCoords;
return createFeature(entity.closed ? 'Polygon' : 'LineString',
entity.closed ? [coords] : coords,
{
style: {
"stroke-color": getColorByColorTable(entity.colorIndex), "stroke-width": 1
}
});
} else if (entity.type === 'CIRCLE') {
return createFeature('Point',
entity.normalizedCoords[0],
{
style: {
"circle-radius": entity.radius,
"stroke-color": getColorByColorTable(entity.colorIndex), "stroke-width": 1
}
});
} else if (entity.type === 'ARC') {
return createFeature('LineString',
entity.normalizedCoords,
{
style: {"stroke-color": getColorByColorTable(entity.colorIndex), "stroke-width": 1}
});
} else if (entity.type === 'POINT') {
return createFeature('Point',
entity.normalizedCoords[0],
{
style: {"stroke-color": getColorByColorTable(entity.colorIndex), "stroke-width": 1}
});
} else if (entity.type === 'SPLINE') {
return createFeature('LineString',
entity.normalizedCoords,
{
style: {"stroke-color": getColorByColorTable(entity.colorIndex), "stroke-width": 1}
});
}
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);
}
vectorSource = new ol.source.Vector({
features: new ol.format.KML({extractStyles: false}).readFeatures(kml, {
featureProjection: 'EPSG:3857',
})
});
// Подписываемся на событие добавления фичи
vectorSource.on("addfeature", (event) => {
createStyleForm(event.feature);
});
initializeForm();
vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: createStyleFromFeature
});
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);
}
vectorSource = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(geojson, {
featureProjection: 'EPSG:3857'
})
});
// Подписываемся на событие добавления фичи
vectorSource.on("addfeature", (event) => {
createStyleForm(event.feature);
});
// Инициализируем форму стилем из первой фичи
initializeForm();
vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: createStyleFromFeature // Используем функцию для создания стиля
});
map.addLayer(vectorLayer);
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 XOffset = parseInt(document.getElementById("XOffsetField").value)
const YOffset = parseInt(document.getElementById("YOffsetField").value)
if (XOffset && YOffset) {
y += XOffset // X попр
x += YOffset // 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 %}