381 lines
16 KiB
HTML
381 lines
16 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;
|
||
}
|
||
</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>
|
||
<input type="text" class="form-control" id="name"
|
||
placeholder="Введите имя слоя">
|
||
</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">
|
||
<input type="hidden" name="id_file"
|
||
class="form-control"
|
||
autofocus=""
|
||
id="id_file" style="visibility:hidden; display: none"
|
||
accept=".json">
|
||
</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>
|
||
</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}}')
|
||
console.log(centerLat)
|
||
let i = 0
|
||
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', 'Ортофотоплан')
|
||
|
||
const map = new ol.Map({
|
||
target: 'map',
|
||
layers: [
|
||
new ol.layer.Tile({
|
||
source: new ol.source.OSM()
|
||
}),
|
||
scanLayer
|
||
],
|
||
view: new ol.View({
|
||
center: ol.proj.fromLonLat([centerLon, centerLat]), // Центр карты
|
||
zoom: 12,
|
||
})
|
||
});
|
||
let vectorLayer;
|
||
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 parser = new DxfParser();
|
||
try {
|
||
const dxf = parser.parseSync(e.target.result);
|
||
const geojson = dxfToGeoJSON(dxf);
|
||
addGeoJSONToMap(geojson);
|
||
} catch (error) {
|
||
console.error('DXF Parsing Error:', error);
|
||
}
|
||
};
|
||
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]];
|
||
}
|
||
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);
|
||
} else if (entity.type === 'LWPOLYLINE' || entity.type === 'POLYLINE') {
|
||
const coords = entity.normalizedCoords;
|
||
return createFeature(entity.closed ? 'Polygon' : 'LineString', entity.closed ? [coords] : coords);
|
||
} else if (entity.type === 'CIRCLE') {
|
||
return createFeature('Point', entity.normalizedCoords[0], {radius: entity.radius});
|
||
} else if (entity.type === 'ARC') {
|
||
return createFeature('LineString', entity.normalizedCoords);
|
||
} else if (entity.type === 'POINT') {
|
||
return createFeature('Point', entity.normalizedCoords[0]);
|
||
} else if (entity.type === 'SPLINE') {
|
||
return createFeature('LineString', entity.normalizedCoords);
|
||
}
|
||
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 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: 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);
|
||
const group = new ol.Collection(vectorSource.getFeatures());
|
||
// Добавляем возможность перетаскивания
|
||
const translateInteraction = new ol.interaction.Translate({
|
||
features: group,
|
||
});
|
||
map.addInteraction(translateInteraction);
|
||
|
||
// Добавляем возможность масштабирования и перемещения с помощью маркеров
|
||
const transformInteraction = new ol.interaction.Transform({
|
||
features: group,
|
||
addCondition: ol.events.condition.shiftKeyOnly
|
||
});
|
||
map.addInteraction(transformInteraction);
|
||
|
||
// Выделение всех фичей
|
||
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('DXF не содержит геометрических объектов.');
|
||
}
|
||
}
|
||
|
||
function convertToLonLat([x, y]) {
|
||
|
||
const kx = 1.676;
|
||
const ky = 1.001;
|
||
|
||
console.log(`Координаты до конвертации [${x},${y}]`)
|
||
res = ol.proj.transform([x, y], 'EPSG:3857', 'EPSG:4326')
|
||
console.log(`Координаты после конвертации [${res[0]},${res[1]}]`)
|
||
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'});
|
||
console.log(blob)
|
||
const url = URL.createObjectURL(blob);
|
||
console.log(url)
|
||
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("#name")
|
||
|
||
const formData = new FormData();
|
||
formData.append('file', new Blob([geojson], {type: 'application/json'}), 'export.geojson');
|
||
formData.append('name', name.value)
|
||
|
||
// Отправляем данные на сервер
|
||
fetch('{% url "create_layer" %}', {
|
||
method: 'POST',
|
||
body: formData,
|
||
headers: {
|
||
'X-CSRFToken': '{{ csrf_token }}' // Добавляем CSRF-токен для защиты
|
||
}
|
||
}).then(response => {
|
||
if (response.ok) {
|
||
console.log('Файл успешно сохранен!');
|
||
window.location.href = '/main/'
|
||
} else {
|
||
console.error('Ошибка при сохранении файла.');
|
||
}
|
||
}).catch(error => {
|
||
console.error('Ошибка:', error);
|
||
});
|
||
} else {
|
||
console.error('Нет данных для сохранения.');
|
||
}
|
||
});
|
||
|
||
</script>
|
||
{% endblock %} |