test/apps/main/templates/create_layer.html

1071 lines
48 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' %}">
<link rel="stylesheet" href="{% static 'css/create_layer.css' %}?ver={% settings_value 'APP_VER' %}">
<style>
</style>
<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-5 col-sm-12">
<div class="card card-primary card-outline card-tabs h-100">
<div class="card-header p-0 pt-1 border-bottom-0">
<ul class="nav nav-tabs" id="custom-tabs-three-tab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="common-properties-tab" data-toggle="pill"
href="#common-properties" role="tab"
aria-controls="common-properties" aria-selected="true">
Общие данные
</a>
</li>
<li class="nav-item">
<a class="nav-link" id="style-properties-tab" data-toggle="pill"
href="#style-properties" role="tab"
aria-controls="style-properties" aria-selected="false">
Внешний вид
</a>
</li>
</ul>
</div>
<div class="card-body">
<div class="tab-content" id="custom-tabs-three-tabContent">
<div class="tab-pane fade show active" id="common-properties" role="tabpanel"
aria-labelledby="common-properties-tab">
<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"></span></span>
<input type="file" name="layer_file_input"
class="form-control"
autofocus=""
id="id_layer_file_input"
accept=".kml, .json, .geojson, .dxf">
{{ form.file.as_hidden }}
</div>
</div>
</div>
<div class="tab-pane fade" id="style-properties" role="tabpanel"
aria-labelledby="style-properties-tab">
<div id="style-editor-container">
<div class="row">
<div class="col-5 col-sm-3">
<div id="vert-tabs-tab"
role="tablist" aria-orientation="vertical"
class="nav nav-pills">
</div>
</div>
<div class="col-7 col-sm-9">
<div class="tab-content" id="style-tabContent">
<h6
>Для стилизации слоя - загрузите файл!</h6>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.card -->
</div>
</div>
<div class="col-md-7 col-sm-12">
<div class="card card-primary card-outline 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 " style="gap: 30px">
<div class="custom-control custom-radio">
<input class="custom-control-input" type="radio" id="modeChangeRadio2"
name="modeChangeRadio" value="crop">
<label for="modeChangeRadio2" class="custom-control-label">Режим обрезки (Необходимо
зажать ALT)</label>
</div>
<div class="custom-control custom-radio">
<input class="custom-control-input" type="radio" id="modeChangeRadio1"
name="modeChangeRadio" value="scaling">
<label for="modeChangeRadio1" class="custom-control-label">Режим
масштабирования</label>
</div>
{% if request.user.is_superuser %}
<button type="button" id="exportGeoJSON" class="btn btn-info float-right">
Экспортировать GeoJSON
</button>
{% endif %}
</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 setSelectionToGroup() {
transformInteraction.setSelection(group);
}
function removeFeaturesOutsideExtent(extent) {
console.log("Removing features outside extent:", extent);
const features = vectorSource.getFeatures();
features.forEach((feature) => {
const geometry = feature.getGeometry();
if (!geometry.intersectsExtent(extent)) {
vectorSource.removeFeature(feature); // Удаляем фичу, если она вне extent
}
});
}
const degreesToRadians = (degrees) => (degrees * Math.PI) / 180;
function decodeDXFText(text) {
// Заменяем Unicode коды на символы
text = text.replace(/\\U\+([\dA-F]{4})/gi, (_, code) =>
String.fromCharCode(parseInt(code, 16))
);
// Убираем символы \pi и заменяем \P на перенос строки
text = text.replace(/\\pi\d+\.\d+/g, ''); // Убираем управляющие коды \pi
text = text.replace(/\\P/g, '\n'); // Заменяем \P на перенос строки
return text;
}
let previousChoice;
let isDrawing = false; // Флаг для отслеживания состояния рисования
// Функция для очистки всех взаимодействий и обработчиков событий
function cleanupInteractions() {
map.un("pointermove", setSelectionToGroup); // Убираем обработчик pointermove
map.un("pointerdown", handlePointerDown); // Убираем обработчик pointerdown
map.un("pointerup", handlePointerUp); // Убираем обработчик pointerup
map.removeInteraction(extentInteraction); // Убираем extentInteraction
map.removeInteraction(transformInteraction); // Убираем transformInteraction
}
// Обработчик для pointerdown
function handlePointerDown() {
isDrawing = true; // Начало рисования
}
// Обработчик для pointerup
function handlePointerUp() {
if (isDrawing) {
const extent = extentInteraction.getExtent();
removeFeaturesOutsideExtent(extent);
isDrawing = false; // Конец рисования
}
}
document.querySelectorAll('input[type="radio"][name="modeChangeRadio"]').forEach((button) => {
button.addEventListener('change', function () {
if (this.checked) {
// Очищаем все предыдущие взаимодействия и обработчики
cleanupInteractions();
if (this.value === "crop") {
// Отключаем DragPan, чтобы карта не перемещалась при рисовании extent
map.getInteractions().forEach((interaction) => {
if (interaction instanceof ol.interaction.DragPan) {
interaction.setActive(false);
}
});
// Добавляем взаимодействие для выделения extent
map.addInteraction(extentInteraction);
// Добавляем обработчики событий для pointerdown и pointerup
map.on("pointerdown", handlePointerDown);
map.on("pointerup", handlePointerUp);
// Подписываемся на событие изменения extent
extentInteraction.on("extentchanged", () => {
// Здесь можно добавить логику для обновления UI или других элементов
});
} else if (this.value === "scaling") {
// Включаем DragPan обратно, чтобы карта могла перемещаться
map.getInteractions().forEach((interaction) => {
if (interaction instanceof ol.interaction.DragPan) {
interaction.setActive(true);
}
});
// Добавляем возможность масштабирования и перемещения с помощью маркеров
map.addInteraction(transformInteraction);
// Обновляем выделение при перемещении мыши
map.on('pointermove', setSelectionToGroup);
}
previousChoice = this.value;
}
});
});
</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 translateInteraction = {}
let extentInteraction = {}
let i = 0
const scanLayerExists = Boolean(parseInt('{{ scan_layer_enable }}'))
let vectorSource = {}
let vectorLayer = {}
let group = {}
const DXFLayersList = []
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 createStyleFromFeature = function (feature, resolution) {
// Получаем стили из feature
const styleProperties = feature.get("style");
// Если стили заданы, создаем стиль на их основе
if (styleProperties) {
const stroke = styleProperties["stroke-color"] || styleProperties["stroke-width"]
? new ol.style.Stroke({
color: styleProperties["stroke-color"] || "blue",
width: styleProperties["stroke-width"] || 2,
lineDash: styleProperties['stroke-line-dash']
})
: null;
const fill = styleProperties["fill-color"] ? new ol.style.Fill({
color: styleProperties["fill-color"]
}) : null;
const zoom = map.getView().getZoom();
const text = zoom > 12
? new ol.style.Text({
text: styleProperties["text-value"],
font: styleProperties["text-font"] || "14px Calibri,sans-serif",
fill: new ol.style.Fill({
color: styleProperties["text-color"] || styleProperties["stroke-color"] || "white"
}),
scale: 1,
offsetX: styleProperties["text-offset-x"] || 0,
offsetY: styleProperties["text-offset-y"] || 0,
textAlign: styleProperties["text-align"] || "center",
textBaseline: styleProperties["text-baseline"] || "middle",
rotation: styleProperties['text-rotation'] || 0
})
: null;
return new ol.style.Style({
stroke: stroke,
fill: fill,
text: text
});
}
// Дефолтный стиль
return new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 0, 0, 0.5)'
}),
stroke: new ol.style.Stroke({
color: 'blue',
width: 2
}),
text: new ol.style.Text({
// text: 'Hello, OpenLayers!',
font: '14px Calibri,sans-serif',
fill: new ol.style.Fill({
color: 'white'
}),
offsetX: 0,
offsetY: -20,
textAlign: 'center',
textBaseline: 'middle'
})
});
};
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({
translateFeature: false
});
// Выделение зоны
extentInteraction = new ol.interaction.Extent({
condition: ol.events.condition.altKeyOnly
})
// Дефолтные значения стиля
const DEFAULT_STYLE = {
"stroke-color": "#0000ff",
"stroke-width": 2,
"stroke-line-dash": undefined
};
// Функция для обновления стиля слоя
function updateLayerStyle(event) {
const form = document.getElementById("style-editor");
const input = event.target
// Обновляем стиль для всех фич в слое
vectorSource.getFeatures()
.filter((feature) => feature.get('layer') === input.dataset.layer)
.forEach((feature) => {
const currentStyle = feature.get("style") || {};
const property = input.id.split('_')[0];
currentStyle[property] = input.type === "number" ? parseFloat(input.value) : input.value;
// Устанавливаем обновленный стиль
feature.set("style", currentStyle);
});
// Обновляем слой
vectorLayer.changed();
}
function updateLayerStyleSelect(event) {
const propertiesMap = {
"solid": undefined,
"dash-dot": [5, 2.5, 0, 2.5],
"dot": [0, 2.5],
}
const input = event.target
// Обновляем стиль для всех фич в слое
vectorSource.getFeatures()
.filter((feature) => feature.get('layer') === input.dataset.layer)
.forEach((feature) => {
const currentStyle = feature.get("style") || {};
const property = input.id.split('_')[0];
currentStyle[property] = propertiesMap[input.value];
// Устанавливаем обновленный стиль
feature.set("style", currentStyle);
});
// Обновляем слой
vectorLayer.changed();
}
function getLabelForProperty(property) {
switch (property) {
case "stroke-color":
return "Цвет линии:"
case "stroke-width":
return "Ширина линии:"
case "stroke-line-dash":
return "Тип линии:"
}
}
// Функция для создания формы на основе свойств стиля
function createStyleForm(feature, layerName = "0", sinlgeLayer = false) {
// Список свойств стиля для отображения в форме
const styleProperties = Object.keys(DEFAULT_STYLE);
const style = feature.get("style") || DEFAULT_STYLE; // Используем стиль из фичи или по умолчанию
const container = document.getElementById("style-editor-container");
const tabContent = document.getElementById('style-tabContent')
const tabList = document.getElementById('vert-tabs-tab')
// Элемент списка слева
const tabLink = document.createElement('a')
tabLink.className = 'nav-link'
tabLink.id = `layer_${layerName}-tab`
tabLink.href = `#layer_${layerName}`
tabLink.role = 'tab'
tabLink.setAttribute('data-toggle', "pill")
tabLink.setAttribute('aria-controls', `layer_${layerName}`)
tabLink.ariaSelected = 'false'
tabLink.textContent = `Слой ${layerName}`
if (sinlgeLayer) {
tabLink.classList.add("active")
}
tabList.appendChild(tabLink)
// Заголовок
const tabPane = document.createElement('div')
tabPane.className = 'tab-pane text-left fade'
tabPane.id = `layer_${layerName}`
tabPane.role = 'tabpanel'
tabPane.setAttribute("aria-labelledby", `layer_${layerName}-tab`)
if (sinlgeLayer) {
tabPane.classList.add("active", "show")
}
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 = layerName ? `${property}_${layerName}` : property;
input.dataset.layer = layerName
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}_${layerName}`
input.dataset.layer = layerName
input.value = rgbToHex(style[property]) || DEFAULT_STYLE[property];
input.className = "form-control";
} else if (property === "stroke-line-dash") {
input = document.createElement("select");
input.id = `${property}_${layerName}`
input.dataset.layer = layerName
input.className = "form-control";
const solid = document.createElement("option");
solid.text = "Сплошная"
solid.value = 'solid'
const dashDot = document.createElement("option");
dashDot.text = "Штрихпунктирная"
dashDot.value = 'dash-dot'
const dot = document.createElement("option");
dot.text = "Пунктирная"
dot.value = 'dot'
input.add(solid)
input.add(dashDot)
input.add(dot)
}
col.appendChild(label);
col.appendChild(input);
row.appendChild(col);
});
tabPane.appendChild(row)
tabContent.appendChild(tabPane)
// Добавляем форму в контейнер
// Добавляем обработчики событий для полей ввода
tabContent.querySelectorAll("input").forEach((input) => {
if (input.type === "color" || input.type === "number") {
input.addEventListener("input", updateLayerStyle);
}
});
tabContent.querySelectorAll("select").forEach((select) => {
select.addEventListener("input", updateLayerStyleSelect);
});
}
// Функция для инициализации формы при загрузке
function initializeForm(dxfLayers = undefined) {
document.getElementById("style-tabContent").innerHTML = "";
document.getElementById("vert-tabs-tab").innerHTML = "";
const features = vectorSource.getFeatures();
if (dxfLayers) {
for (let layer in dxfLayers) {
const byLayer = features.filter((feature) => feature.get('layer') === layer)
const firstFeatureInLayer = byLayer[0]
if (firstFeatureInLayer !== undefined) {
createStyleForm(firstFeatureInLayer, layer);
}
}
return
}
if (features.length > 0) {
const firstFeature = features[0];
console.log(firstFeature, firstFeature.get('layer'))
createStyleForm(firstFeature, firstFeature.get('layer'), true);
}
}
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();
if (dxf.tables.layer) {
addGeoJSONToMap(geojson, dxf.tables.layer.layers);
} else {
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]);
}
if (entity.type === 'TEXT') {
return [[entity.startPoint.x, entity.startPoint.y]]
}
if (entity.type === 'MTEXT') {
return [[entity.position.x, entity.position.y]]
}
return [];
}
function normalizeCoordinates(entities, dxfHeader) {
return entities.map(entity => {
const coords = getCoordinates(entity).map(([x, y]) => {
const XOffset = parseInt(document.getElementById("XOffsetField").value)
const YOffset = parseInt(document.getElementById("YOffsetField").value)
return convertToLonLat([x, y], XOffset, YOffset);
});
return {...entity, normalizedCoords: coords};
});
}
function getStyleFromDXFEntity(entity, lineTypes = undefined) {
const figureStyle = {
"stroke-color": getColorByColorTable(entity.colorIndex),
"stroke-width": 1,
}
if (entity.text && !entity.text.includes('<27>')) {
figureStyle["text-value"] = entity.type === "TEXT" ? entity.text : decodeDXFText(entity.text)
figureStyle["text-rotation"] = -degreesToRadians(entity.rotation)
}
if (lineTypes && entity.lineType) {
if (lineTypes[entity.lineType] && (entity.lineType !== "Continuous" && entity.lineType !== 'HIDDEN')) {
if (lineTypes[entity.lineType].pattern.length > 1)
figureStyle["stroke-line-dash"] = lineTypes[entity.lineType].pattern.map(num => Math.abs(num) * 10)
}
}
return figureStyle
}
function dxfToGeoJSON(dxf) {
console.log(dxf);
const normalizedEntities = normalizeCoordinates(dxf.entities, dxf.header);
let features = [];
normalizedEntities.forEach(entity => {
DXFLayersList.push(entity.layer);
// Обрабатываем обычные сущности
let feature = null;
if (entity.type === 'LINE') {
feature = createFeature('LineString',
entity.normalizedCoords,
{
style: {
"stroke-color": getColorByColorTable(entity.colorIndex),
"stroke-width": 1,
},
"layer": entity.layer
});
} else if (entity.type === 'LWPOLYLINE' || entity.type === 'POLYLINE') {
const coords = entity.normalizedCoords;
// Для замкнутых полилиний добавляем первую точку в конец
if (entity.shape && coords.length > 0) {
coords.push(coords[0]); // Замыкаем полигон
}
feature = createFeature(
entity.shape ? 'Polygon' : 'LineString',
entity.shape ? [coords] : coords,
{
style: {
...getStyleFromDXFEntity(entity, dxf.tables.lineType?.lineTypes),
},
"layer": entity.layer
}
);
} else if (entity.type === 'TEXT' || entity.type === 'MTEXT') {
feature = createFeature('Point',
entity.normalizedCoords[0],
{
style: {
...getStyleFromDXFEntity(entity)
},
"layer": entity.layer
});
} else if (entity.type === 'CIRCLE') {
feature = createFeature('Point',
entity.normalizedCoords[0],
{
style: {
...getStyleFromDXFEntity(entity, dxf.tables.lineType?.lineTypes)
},
"layer": entity.layer
});
} else if (entity.type === 'ARC') {
feature = createFeature('LineString',
entity.normalizedCoords,
{
style: {
...getStyleFromDXFEntity(entity, dxf.tables.lineType?.lineTypes)
},
"layer": entity.layer
});
} else if (entity.type === 'POINT') {
feature = createFeature('Point',
entity.normalizedCoords[0],
{
style: {
...getStyleFromDXFEntity(entity, dxf.tables.lineType?.lineTypes)
},
"layer": entity.layer
});
} else if (entity.type === 'SPLINE') {
feature = createFeature('LineString',
entity.normalizedCoords,
{
style: {
...getStyleFromDXFEntity(entity, dxf.tables.lineType?.lineTypes)
},
"layer": entity.layer
});
}
if (feature) {
features.push(feature);
}
});
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 kmlFeatures = new ol.format.KML({extractStyles: false}).readFeatures(kml, {
featureProjection: 'EPSG:3857',
})
kmlFeatures.forEach(feature => {
feature.set('layer', 'kml')
})
vectorSource = new ol.source.Vector({
features: kmlFeatures
});
// Подписываемся на событие добавления фичи
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();
group = new ol.Collection(features);
const extent = vectorSource.getExtent();
if (!ol.extent.isEmpty(extent)) {
map.getView().fit(extent, {padding: [20, 20, 20, 20]});
} else {
console.warn('Слой не содержит геометрических объектов.');
}
}
function addGeoJSONToMap(geojson, dxfLayers = undefined) {
if (vectorLayer) {
map.removeLayer(vectorLayer);
}
const geoJSONFeatures = new ol.format.GeoJSON().readFeatures(geojson, {
featureProjection: 'EPSG:3857'
})
geoJSONFeatures.forEach(feature => {
if (!feature.get('layer')) {
feature.set('layer', 'geojson')
}
})
vectorSource = new ol.source.Vector({
features: geoJSONFeatures
});
vectorSource.on("addfeature", (event) => {
createStyleForm(event.feature);
});
initializeForm(dxfLayers);
vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: createStyleFromFeature // Используем функцию для создания стиля
});
map.addLayer(vectorLayer);
const features = vectorSource.getFeatures();
group = new ol.Collection(features);
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], XOffset = 0, YOffset = 0) {
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 (event) {
event.target.insertAdjacentHTML('afterbegin', `
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
`);
event.target.disabled = true
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();
}
// Если редактирование слоя
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 %}