Удалил ненужные файлы
This commit is contained in:
parent
c29dca5d2d
commit
b343fd85cc
@ -1,319 +0,0 @@
|
||||
<script>
|
||||
var executed = 0
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (executed === 0) {
|
||||
executed = 1
|
||||
let map = {}
|
||||
let popover;
|
||||
let VlocationLayer = {}
|
||||
let VlocationSource = {}
|
||||
let VlocationMarkers = {}
|
||||
|
||||
let PolygonsLayer = {}
|
||||
let PolygonsSource = {}
|
||||
let PolygonsMarkers = {}
|
||||
|
||||
let polygonCounts = {};
|
||||
|
||||
let popup = {}
|
||||
const propertiesTranslate = {
|
||||
name: "Имя",
|
||||
sn: "Серийный номер",
|
||||
lat: "Широта",
|
||||
lon: "Долгота",
|
||||
alt: "Высота",
|
||||
date_time: "Время координаты",
|
||||
}
|
||||
|
||||
function createWorkersTableRow(worker) {
|
||||
const tr = document.createElement('tr')
|
||||
|
||||
const tdWorkerID = document.createElement('td')
|
||||
tdWorkerID.className = 'p-1 pl-2'
|
||||
{#tdWorkerID.innerHTML = `<a href="workers/edit/${worker.id}/">${worker.name}</a>`#}
|
||||
tdWorkerID.textContent = worker.name
|
||||
const tdWorkerCoord = document.createElement('td')
|
||||
tdWorkerCoord.className = 'p-1 pl-2'
|
||||
|
||||
const showCoordButton = document.createElement('a')
|
||||
showCoordButton.className = 'worker-show-button'
|
||||
showCoordButton.style.cursor = 'pointer'
|
||||
showCoordButton.dataset.worker_id = worker.id
|
||||
showCoordButton.textContent = "Показать на карте"
|
||||
showCoordButton.addEventListener('click', (ev) => {
|
||||
const feature = VlocationMarkers[ev.target.dataset.worker_id];
|
||||
const featureCoords = feature.getGeometry().getCoordinates();
|
||||
// Устанавливаем новый вид карты
|
||||
map.getView().animate({
|
||||
center: featureCoords,
|
||||
zoom: 17,
|
||||
duration: 1000,
|
||||
});
|
||||
setTimeout(() => {
|
||||
showPopover(feature, featureCoords)
|
||||
}, 1001)
|
||||
});
|
||||
tdWorkerCoord.appendChild(showCoordButton)
|
||||
|
||||
|
||||
tr.appendChild(tdWorkerID)
|
||||
tr.appendChild(tdWorkerCoord)
|
||||
return tr
|
||||
}
|
||||
|
||||
function showPopover(feature, coordinates) {
|
||||
// Удаление существующего popover
|
||||
disposePopover();
|
||||
|
||||
// Получение контейнера элемента popup
|
||||
const element = document.getElementById('popup'); // Убедитесь, что этот элемент существует в DOM
|
||||
|
||||
// Установка позиции popup на карте
|
||||
popup.setPosition(coordinates);
|
||||
|
||||
// Создание нового popover
|
||||
popover = new bootstrap.Popover(element, {
|
||||
placement: 'top', // Расположение popover
|
||||
html: true, // Поддержка HTML-содержимого
|
||||
content: createPopover(feature),
|
||||
});
|
||||
|
||||
// Отображение popover
|
||||
popover.show();
|
||||
}
|
||||
|
||||
function disposePopover() {
|
||||
if (popover) {
|
||||
popover.dispose();
|
||||
popover = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function createPopover(feature) {
|
||||
const res = document.createElement('div')
|
||||
const properties = feature.getProperties()
|
||||
for (let property in properties) {
|
||||
if (property === 'geometry' || property === 'id') continue
|
||||
let div = document.createElement('div')
|
||||
let span = document.createElement('span')
|
||||
let strong = document.createElement('strong')
|
||||
strong.textContent = `${propertiesTranslate[property]}: `
|
||||
div.appendChild(strong)
|
||||
|
||||
span.textContent = feature.get(property)
|
||||
div.appendChild(span)
|
||||
|
||||
res.appendChild(div)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
function VlocationStyleFunction(feature, resolution) {
|
||||
return new ol.style.Style({
|
||||
image: new ol.style.Icon({
|
||||
src: '/static/street_pos/img/worker.png',
|
||||
width: 25,
|
||||
height: 30
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function moveMarker(marker, newCoordinates) {
|
||||
const duration = 2000; // Длительность анимации в миллисекундах
|
||||
const startCoordinates = marker.getGeometry().getCoordinates();
|
||||
|
||||
// Начало анимации
|
||||
const startTime = performance.now();
|
||||
|
||||
function animate(currentTime) {
|
||||
// Вычисление прошедшего времени
|
||||
const elapsed = currentTime - startTime;
|
||||
|
||||
// Вычисление доли анимации (от 0 до 1)
|
||||
const fraction = Math.min(elapsed / duration, 1);
|
||||
|
||||
// Интерполяция координат
|
||||
const interpolatedCoordinates = [
|
||||
startCoordinates[0] + fraction * (newCoordinates[0] - startCoordinates[0]),
|
||||
startCoordinates[1] + fraction * (newCoordinates[1] - startCoordinates[1]),
|
||||
];
|
||||
|
||||
// Устанавливаем новые координаты для маркера
|
||||
marker.getGeometry().setCoordinates(interpolatedCoordinates);
|
||||
|
||||
// Продолжаем анимацию, если она еще не завершена
|
||||
if (fraction < 1) {
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
}
|
||||
|
||||
// Запуск анимации
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
|
||||
function initializeMap() {
|
||||
// Источник данных для маркеров
|
||||
VlocationSource = new ol.source.Vector();
|
||||
|
||||
// Слой для отображения маркеров
|
||||
VlocationLayer = new ol.layer.Vector({
|
||||
source: VlocationSource,
|
||||
style: VlocationStyleFunction
|
||||
});
|
||||
PolygonsLayer = new ol.layer.Vector({
|
||||
source: new ol.source.Vector({
|
||||
url: '{% url "main:poligon_list_api" %}',
|
||||
format: new ol.format.GeoJSON(),
|
||||
}),
|
||||
style: polygonBrownStyleFunction,
|
||||
});
|
||||
|
||||
function polygonBrownStyleFunction(feature, resolution) {
|
||||
return new ol.style.Style({
|
||||
stroke: new ol.style.Stroke({
|
||||
color: 'rgb(199,136,10)',
|
||||
width: 2,
|
||||
}),
|
||||
fill: new ol.style.Fill({
|
||||
color: 'rgba(199,136,10, 0.6)',
|
||||
}),
|
||||
text: createTextStyle(feature, resolution)
|
||||
});
|
||||
}
|
||||
|
||||
// Модифицируем функцию getPolygonText
|
||||
const getPolygonText = function (feature) {
|
||||
const polygonId = feature.get('pk');
|
||||
const count = polygonCounts[polygonId] || 0;
|
||||
return `${feature.get('name')} (${count})`;
|
||||
};
|
||||
|
||||
const createTextStyle = function (feature, resolution) {
|
||||
const zoom = map.getView().getZoom();
|
||||
const font = 'bold' + ' ' + zoom + 'px' + '/' + '1' + ' ' + 'Arial';
|
||||
return new ol.style.Text({
|
||||
textAlign: 'center',
|
||||
textBaseline: 'middle',
|
||||
font: font,
|
||||
text: getPolygonText(feature),
|
||||
fill: new ol.style.Fill({color: '#000'}),
|
||||
placement: 'point',
|
||||
scale: 1,
|
||||
overflow: 'false',
|
||||
});
|
||||
};
|
||||
|
||||
PolygonsLayer.set('title', 'Зоны')
|
||||
// Создание карты
|
||||
map = new ol.Map({
|
||||
target: 'map', // ID элемента, куда встроится карта
|
||||
controls: [
|
||||
new ol.control.FullScreen(),
|
||||
new ol.control.ScaleLine(),
|
||||
new ol.control.ZoomSlider()
|
||||
],
|
||||
layers: [
|
||||
new ol.layer.Tile({
|
||||
source: new ol.source.OSM(), // Open street Map
|
||||
}),
|
||||
VlocationLayer,
|
||||
PolygonsLayer
|
||||
],
|
||||
view: new ol.View({
|
||||
center: ol.proj.fromLonLat(['{{lon}}', '{{lat}}']), // Центр карты
|
||||
zoom: 12,
|
||||
}),
|
||||
});
|
||||
|
||||
const element = document.getElementById('popup')
|
||||
// Всплывающее окно
|
||||
popup = new ol.Overlay({
|
||||
element: element,
|
||||
positioning: 'bottom-center',
|
||||
});
|
||||
map.addOverlay(popup);
|
||||
|
||||
|
||||
map.on('movestart', disposePopover);
|
||||
|
||||
// Обработчик клика на карту
|
||||
map.on('click', function (evt) {
|
||||
// Получение feature по клику
|
||||
const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
|
||||
return feature;
|
||||
});
|
||||
|
||||
if (!feature) {
|
||||
disposePopover(); // Если feature не найден, закрываем popover
|
||||
return;
|
||||
}
|
||||
|
||||
// Получение координат клика
|
||||
const coordinates = evt.coordinate;
|
||||
|
||||
// Отображаем popover на фиче
|
||||
showPopover(feature, coordinates);
|
||||
})
|
||||
|
||||
// Загрузка маркеров
|
||||
updateMarkers();
|
||||
setInterval(updateMarkers, 2000);
|
||||
}
|
||||
|
||||
function addVlocationMarker(worker) {
|
||||
const point = new ol.geom.Point(ol.proj.fromLonLat([worker.lon, worker.lat]));
|
||||
const feature = new ol.Feature(point);
|
||||
updateMarkerProperties(feature, worker)
|
||||
VlocationSource.addFeature(feature)
|
||||
VlocationMarkers[worker.id] = feature
|
||||
}
|
||||
|
||||
function updateMarkers() {
|
||||
fetch('{% url "street_pos:tags_list_api" %}')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
data.items.forEach(worker => {
|
||||
if (VlocationMarkers[worker.id]) {
|
||||
const marker = VlocationMarkers[worker.id];
|
||||
|
||||
updateMarkerProperties(marker, worker)
|
||||
|
||||
const currentCoordinates = marker.getGeometry().getCoordinates();
|
||||
const newCoordinates = ol.proj.fromLonLat([worker.lon, worker.lat]);
|
||||
|
||||
// Проверяем, изменились ли координаты
|
||||
if (currentCoordinates[0] !== newCoordinates[0] || currentCoordinates[1] !== newCoordinates[1]) {
|
||||
moveMarker(marker, newCoordinates); // Плавное перемещение
|
||||
}
|
||||
} else {
|
||||
// Создаем новый маркер, если его ещё нет
|
||||
addVlocationMarker(worker);
|
||||
}
|
||||
});
|
||||
});
|
||||
fetch('{% url "main:poligon_count_api" %}') // Замените на ваш endpoint
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
// Обновляем данные о количестве
|
||||
data.items.forEach(item => {
|
||||
polygonCounts[item.id] = item.count;
|
||||
});
|
||||
// Обновляем стили полигонов, чтобы текст перерисовался
|
||||
PolygonsLayer.getSource().forEachFeature(feature => {
|
||||
feature.changed();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function updateMarkerProperties(marker, properties) {
|
||||
for (let property in properties) {
|
||||
marker.set(property, properties[property])
|
||||
}
|
||||
}
|
||||
|
||||
initializeMap()
|
||||
}
|
||||
})
|
||||
|
||||
</script>
|
||||
@ -1,262 +0,0 @@
|
||||
<script>
|
||||
var executed = 0
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (executed === 0) {
|
||||
executed = 1
|
||||
let map = {}
|
||||
let popover;
|
||||
let VlocationLayer = {}
|
||||
let VlocationSource = {}
|
||||
let popup = {}
|
||||
let VlocationMarkers = {}
|
||||
const propertiesTranslate = {
|
||||
name: "Имя",
|
||||
sn: "Серийный номер",
|
||||
lat: "Широта",
|
||||
lon: "Долгота",
|
||||
alt: "Высота",
|
||||
date_time: "Время координаты",
|
||||
}
|
||||
|
||||
function createWorkersTableRow(worker) {
|
||||
const tr = document.createElement('tr')
|
||||
|
||||
const tdWorkerID = document.createElement('td')
|
||||
tdWorkerID.className = 'p-1 pl-2'
|
||||
{#tdWorkerID.innerHTML = `<a href="workers/edit/${worker.id}/">${worker.name}</a>`#}
|
||||
tdWorkerID.textContent = worker.name
|
||||
const tdWorkerCoord = document.createElement('td')
|
||||
tdWorkerCoord.className = 'p-1 pl-2'
|
||||
|
||||
const showCoordButton = document.createElement('a')
|
||||
showCoordButton.className = 'worker-show-button'
|
||||
showCoordButton.style.cursor = 'pointer'
|
||||
showCoordButton.dataset.worker_id = worker.id
|
||||
showCoordButton.textContent = "Показать на карте"
|
||||
showCoordButton.addEventListener('click', (ev) => {
|
||||
const feature = VlocationMarkers[ev.target.dataset.worker_id];
|
||||
const featureCoords = feature.getGeometry().getCoordinates();
|
||||
// Устанавливаем новый вид карты
|
||||
map.getView().animate({
|
||||
center: featureCoords,
|
||||
zoom: 17,
|
||||
duration: 1000,
|
||||
});
|
||||
setTimeout(() => {
|
||||
showPopover(feature, featureCoords)
|
||||
}, 1001)
|
||||
});
|
||||
tdWorkerCoord.appendChild(showCoordButton)
|
||||
|
||||
|
||||
tr.appendChild(tdWorkerID)
|
||||
tr.appendChild(tdWorkerCoord)
|
||||
return tr
|
||||
}
|
||||
|
||||
function showPopover(feature, coordinates) {
|
||||
// Удаление существующего popover
|
||||
disposePopover();
|
||||
|
||||
// Получение контейнера элемента popup
|
||||
const element = document.getElementById('popup'); // Убедитесь, что этот элемент существует в DOM
|
||||
|
||||
// Установка позиции popup на карте
|
||||
popup.setPosition(coordinates);
|
||||
|
||||
// Создание нового popover
|
||||
popover = new bootstrap.Popover(element, {
|
||||
placement: 'top', // Расположение popover
|
||||
html: true, // Поддержка HTML-содержимого
|
||||
content: createPopover(feature),
|
||||
});
|
||||
|
||||
// Отображение popover
|
||||
popover.show();
|
||||
}
|
||||
|
||||
function disposePopover() {
|
||||
if (popover) {
|
||||
popover.dispose();
|
||||
popover = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function createPopover(feature) {
|
||||
const res = document.createElement('div')
|
||||
const properties = feature.getProperties()
|
||||
for (let property in properties) {
|
||||
if (property === 'geometry' || property === 'id') continue
|
||||
let div = document.createElement('div')
|
||||
let span = document.createElement('span')
|
||||
let strong = document.createElement('strong')
|
||||
strong.textContent = `${propertiesTranslate[property]}: `
|
||||
div.appendChild(strong)
|
||||
|
||||
span.textContent = feature.get(property)
|
||||
div.appendChild(span)
|
||||
|
||||
res.appendChild(div)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
function VlocationStyleFunction(feature, resolution) {
|
||||
return new ol.style.Style({
|
||||
image: new ol.style.Icon({
|
||||
src: '/static/street_pos/img/worker.png',
|
||||
width: 25,
|
||||
height: 30
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function moveMarker(marker, newCoordinates) {
|
||||
const duration = 2000; // Длительность анимации в миллисекундах
|
||||
const startCoordinates = marker.getGeometry().getCoordinates();
|
||||
|
||||
// Начало анимации
|
||||
const startTime = performance.now();
|
||||
|
||||
function animate(currentTime) {
|
||||
// Вычисление прошедшего времени
|
||||
const elapsed = currentTime - startTime;
|
||||
|
||||
// Вычисление доли анимации (от 0 до 1)
|
||||
const fraction = Math.min(elapsed / duration, 1);
|
||||
|
||||
// Интерполяция координат
|
||||
const interpolatedCoordinates = [
|
||||
startCoordinates[0] + fraction * (newCoordinates[0] - startCoordinates[0]),
|
||||
startCoordinates[1] + fraction * (newCoordinates[1] - startCoordinates[1]),
|
||||
];
|
||||
|
||||
// Устанавливаем новые координаты для маркера
|
||||
marker.getGeometry().setCoordinates(interpolatedCoordinates);
|
||||
|
||||
// Продолжаем анимацию, если она еще не завершена
|
||||
if (fraction < 1) {
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
}
|
||||
|
||||
// Запуск анимации
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
|
||||
function initializeMap() {
|
||||
// Источник данных для маркеров
|
||||
VlocationSource = new ol.source.Vector();
|
||||
|
||||
// Слой для отображения маркеров
|
||||
VlocationLayer = new ol.layer.Vector({
|
||||
source: VlocationSource,
|
||||
style: VlocationStyleFunction
|
||||
});
|
||||
|
||||
// Создание карты
|
||||
map = new ol.Map({
|
||||
target: 'map', // ID элемента, куда встроится карта
|
||||
controls: [
|
||||
new ol.control.FullScreen(),
|
||||
new ol.control.ScaleLine(),
|
||||
new ol.control.ZoomSlider()
|
||||
],
|
||||
layers: [
|
||||
new ol.layer.Tile({
|
||||
source: new ol.source.OSM(), // Open street Map
|
||||
}),
|
||||
VlocationLayer,
|
||||
],
|
||||
view: new ol.View({
|
||||
center: ol.proj.fromLonLat(['{{lon}}', '{{lat}}']), // Центр карты
|
||||
zoom: 12,
|
||||
}),
|
||||
});
|
||||
|
||||
const element = document.getElementById('popup')
|
||||
// Всплывающее окно
|
||||
popup = new ol.Overlay({
|
||||
element: element,
|
||||
positioning: 'bottom-center',
|
||||
});
|
||||
map.addOverlay(popup);
|
||||
|
||||
|
||||
map.on('movestart', disposePopover);
|
||||
|
||||
// Обработчик клика на карту
|
||||
map.on('click', function (evt) {
|
||||
// Получение feature по клику
|
||||
const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
|
||||
return feature;
|
||||
});
|
||||
|
||||
if (!feature) {
|
||||
disposePopover(); // Если feature не найден, закрываем popover
|
||||
return;
|
||||
}
|
||||
|
||||
// Получение координат клика
|
||||
const coordinates = evt.coordinate;
|
||||
|
||||
// Отображаем popover на фиче
|
||||
showPopover(feature, coordinates);
|
||||
})
|
||||
|
||||
// Загрузка маркеров
|
||||
updateMarkers();
|
||||
setInterval(updateMarkers, 2000);
|
||||
}
|
||||
|
||||
function addVlocationMarker(worker) {
|
||||
const point = new ol.geom.Point(ol.proj.fromLonLat([worker.lon, worker.lat]));
|
||||
const feature = new ol.Feature(point);
|
||||
updateMarkerProperties(feature, worker)
|
||||
VlocationSource.addFeature(feature)
|
||||
VlocationMarkers[worker.id] = feature
|
||||
}
|
||||
|
||||
function updateMarkers() {
|
||||
fetch('update_object/')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const workersTableBody = document.querySelector('#workersTableBody')
|
||||
const workersCount = document.querySelector('#workersCount')
|
||||
workersCount.textContent = `( ${data.total} )`
|
||||
workersTableBody.innerHTML = ''
|
||||
data.items.forEach(worker => {
|
||||
let tableRow = createWorkersTableRow(worker)
|
||||
workersTableBody.appendChild(tableRow)
|
||||
if (VlocationMarkers[worker.id]) {
|
||||
const marker = VlocationMarkers[worker.id];
|
||||
|
||||
updateMarkerProperties(marker, worker)
|
||||
|
||||
const currentCoordinates = marker.getGeometry().getCoordinates();
|
||||
const newCoordinates = ol.proj.fromLonLat([worker.lon, worker.lat]);
|
||||
|
||||
// Проверяем, изменились ли координаты
|
||||
if (currentCoordinates[0] !== newCoordinates[0] || currentCoordinates[1] !== newCoordinates[1]) {
|
||||
moveMarker(marker, newCoordinates); // Плавное перемещение
|
||||
}
|
||||
} else {
|
||||
// Создаем новый маркер, если его ещё нет
|
||||
addVlocationMarker(worker);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function updateMarkerProperties(marker, properties) {
|
||||
for (let property in properties) {
|
||||
marker.set(property, properties[property])
|
||||
}
|
||||
}
|
||||
|
||||
initializeMap()
|
||||
}
|
||||
})
|
||||
|
||||
</script>
|
||||
Loading…
x
Reference in New Issue
Block a user