Минимальная стилизация векторных слоев
This commit is contained in:
parent
1390d0f1c2
commit
27e7425538
@ -80,8 +80,7 @@
|
||||
<h3 class="card-title">Стиль слоя</h3>
|
||||
</div>
|
||||
<!-- form start -->
|
||||
<div class="card-body">
|
||||
</div>
|
||||
<div id="style-editor-container" class="card-body"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-8 col-sm-12">
|
||||
@ -115,9 +114,40 @@
|
||||
<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/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");
|
||||
@ -139,7 +169,7 @@
|
||||
let translateInteraction = {}
|
||||
let i = 0
|
||||
const scanLayerExists = Boolean(parseInt('{{ scan_layer_enable }}'))
|
||||
|
||||
let vectorSource = {}
|
||||
layers = [
|
||||
new ol.layer.Tile({
|
||||
source: new ol.source.OSM()
|
||||
@ -194,23 +224,114 @@
|
||||
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
|
||||
// });
|
||||
// });
|
||||
// Дефолтные значения стиля
|
||||
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];
|
||||
@ -251,66 +372,6 @@
|
||||
}
|
||||
});
|
||||
|
||||
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
|
||||
})
|
||||
: null;
|
||||
|
||||
const fill = styleProperties["fill-color"] ? new ol.style.Fill({
|
||||
color: styleProperties["fill-color"]
|
||||
}) : null;
|
||||
|
||||
const text = styleProperties["text-value"]
|
||||
? 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"] || "white"
|
||||
}),
|
||||
offsetX: styleProperties["text-offset-x"] || 0,
|
||||
offsetY: styleProperties["text-offset-y"] || -20,
|
||||
textAlign: styleProperties["text-align"] || "center",
|
||||
textBaseline: styleProperties["text-baseline"] || "middle"
|
||||
})
|
||||
: 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'
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
function getCoordinates(entity) {
|
||||
if (entity.type === 'LINE') {
|
||||
return [[entity.vertices[0].x, entity.vertices[0].y], [entity.vertices[1].x, entity.vertices[1].y]];
|
||||
@ -431,23 +492,19 @@
|
||||
if (vectorLayer) {
|
||||
map.removeLayer(vectorLayer);
|
||||
}
|
||||
const vectorSource = new ol.source.Vector({
|
||||
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: 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'})
|
||||
})
|
||||
})
|
||||
style: createStyleFromFeature
|
||||
});
|
||||
map.addLayer(vectorLayer);
|
||||
|
||||
@ -460,7 +517,6 @@
|
||||
map.on('pointermove', () => {
|
||||
transformInteraction.setSelection(group);
|
||||
});
|
||||
|
||||
const extent = vectorSource.getExtent();
|
||||
if (!ol.extent.isEmpty(extent)) {
|
||||
map.getView().fit(extent, {padding: [20, 20, 20, 20]});
|
||||
@ -473,14 +529,23 @@
|
||||
if (vectorLayer) {
|
||||
map.removeLayer(vectorLayer);
|
||||
}
|
||||
const vectorSource = new ol.source.Vector({
|
||||
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
|
||||
style: createStyleFromFeature // Используем функцию для создания стиля
|
||||
});
|
||||
map.addLayer(vectorLayer);
|
||||
|
||||
@ -601,6 +666,6 @@
|
||||
.catch(error => console.error('Ошибка загрузки KML:', error));
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
</script>
|
||||
{% endblock %}
|
||||
@ -313,20 +313,6 @@
|
||||
});
|
||||
}
|
||||
|
||||
function polygonBrownStyleFunction(feature, resolution) {
|
||||
return new ol.style.Style({
|
||||
stroke: new ol.style.Stroke({
|
||||
color: feature.get("color") ? feature.get("color") : 'rgb(199,136,10)',
|
||||
width: 2,
|
||||
}),
|
||||
fill: new ol.style.Fill({
|
||||
color: 'rgba(199,136,10, 0.6)',
|
||||
}),
|
||||
text: createGTOZoneNameTextStyle(feature, resolution)
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function moveMarker(marker, newCoordinates) {
|
||||
const duration = 2000; // Длительность анимации в миллисекундах
|
||||
const startCoordinates = marker.getGeometry().getCoordinates();
|
||||
@ -498,7 +484,7 @@
|
||||
format: new ol.format.GeoJSON(),
|
||||
}),
|
||||
visible: layer.is_visible,
|
||||
style: polygonBrownStyleFunction
|
||||
style: createStyleFromFeature
|
||||
});
|
||||
}
|
||||
newLayer.set('title', layer.name)
|
||||
@ -537,22 +523,21 @@
|
||||
}
|
||||
layersBtn.classList.toggle("selected")
|
||||
})
|
||||
// layerSwitcher.addControl(
|
||||
// new ol.control.Button({
|
||||
// html: "Создать слой",
|
||||
// handleClick: function () {
|
||||
// window.location.href = '{% url 'create_layer' %}'
|
||||
// }
|
||||
// }), 'bottom');
|
||||
|
||||
// layerSwitcher.addControl(
|
||||
// new ol.control.Button({
|
||||
// html: "Редактировать слои",
|
||||
// handleClick: function () {
|
||||
// window.location.href = '{% url 'layers_list' %}'
|
||||
// }
|
||||
// }), 'bottom'
|
||||
// );
|
||||
layerSwitcher.addControl(
|
||||
new ol.control.Button({
|
||||
html: "Создать слой",
|
||||
handleClick: function () {
|
||||
window.location.href = '{% url 'create_layer' %}'
|
||||
}
|
||||
}), 'bottom');
|
||||
layerSwitcher.addControl(
|
||||
new ol.control.Button({
|
||||
html: "Редактировать слои",
|
||||
handleClick: function () {
|
||||
window.location.href = '{% url 'layers_list' %}'
|
||||
}
|
||||
}), 'bottom'
|
||||
);
|
||||
|
||||
map.addControl(layerSwitcher)
|
||||
|
||||
|
||||
@ -118,4 +118,65 @@ function polygonBrownStyleFunction(feature, resolution) {
|
||||
}),
|
||||
text: createGTOZoneNameTextStyle(feature, resolution)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
})
|
||||
: null;
|
||||
|
||||
const fill = styleProperties["fill-color"] ? new ol.style.Fill({
|
||||
color: styleProperties["fill-color"]
|
||||
}) : null;
|
||||
|
||||
const text = styleProperties["text-value"]
|
||||
? 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"] || "white"
|
||||
}),
|
||||
offsetX: styleProperties["text-offset-x"] || 0,
|
||||
offsetY: styleProperties["text-offset-y"] || -20,
|
||||
textAlign: styleProperties["text-align"] || "center",
|
||||
textBaseline: styleProperties["text-baseline"] || "middle"
|
||||
})
|
||||
: 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'
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
7611
static/js/ol/proj4js.js
Normal file
7611
static/js/ol/proj4js.js
Normal file
File diff suppressed because it is too large
Load Diff
Loading…
x
Reference in New Issue
Block a user