198 lines
6.2 KiB
JavaScript

const propertiesTranslate = {
name: "Имя",
sn: "Серийный номер",
tag_sn: "Серийный номер",
lat: "Широта",
lon: "Долгота",
alt: "Высота",
time: "Время координаты",
date_time: "Время координаты",
statenum: "Госномер",
garagenum: "Гаражный номер",
model: "Тип",
depth: "Глубина",
magnitude: "Магнитуда",
region: "Регион",
source: "Источник",
uid: "Идентификатор",
description: "Описание"
}
const invisibleProperties = ['id', 'geometry', 'icon', 'condition', 'style', 'layer', 'pk', "colorIndex", "iso_time"]
let popover;
function disposePopover() {
if (popover) {
popover.dispose();
popover = undefined;
}
}
class MapCore {
constructor(mapId, options = {}) {
this.mapId = mapId;
this.options = options;
this.map = null;
this.layers = {
base: [],
static: [],
dynamic: []
};
this.controls = [];
this.markers = {};
this.popup = null;
}
async initialize() {
// Инициализация карты
this.map = new ol.Map({
target: this.mapId,
controls: this.controls,
layers: [],
view: new ol.View({
center: ol.proj.fromLonLat(this.options.center || [0, 0]),
zoom: this.options.zoom || 12
})
});
// Инициализация базовых слоев
await this._initBaseLayers();
this._initPopup();
window.Map_ = this.map
return this;
}
async _initBaseLayers() {
// Добавление OSM слоя
const osmLayer = new ol.layer.Tile({
baseLayer: true,
source: new ol.source.OSM(),
title: 'OpenStreet Map'
});
this.layers.base.push(osmLayer);
// Группировка слоев
const layerGroups = [
new ol.layer.Group({
title: 'Базовые слои',
type: 'base',
layers: this.layers.base,
openInLayerSwitcher: true,
}),
new ol.layer.Group({
title: 'Статические слои',
type: 'static',
layers: this.layers.static,
openInLayerSwitcher: true,
}),
new ol.layer.Group({
title: 'Динамические слои',
type: 'dynamic',
layers: this.layers.dynamic,
openInLayerSwitcher: true,
})
];
this.map.getLayers().extend(layerGroups);
}
_initPopup() {
const element = document.getElementById('popup')
const popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
});
this.map.addOverlay(popup);
this.map.on('click', function (evt) {
// Получение feature по клику
const feature = window.Map_.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
// Удаление существующего popover
disposePopover();
if (!feature) {
return; // Если feature не найден, ничего не делаем
}
// Получение координат клика
const coordinates = evt.coordinate;
// Получение контейнера элемента popup
const element = document.getElementById('popup'); // Убедитесь, что этот элемент существует в DOM
// Установка позиции popup на карте
popup.setPosition(coordinates);
function createPopover(feature) {
const res = document.createElement('div')
const properties = feature.getProperties()
for (let property in properties) {
if (invisibleProperties.includes(property)) 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
}
// Создание нового popover
popover = new bootstrap.Popover(element, {
placement: 'top', // Расположение popover
html: true, // Поддержка HTML-содержимого
content: createPopover(feature),
});
// Отображение popover
popover.show();
});
this.map.on('movestart', disposePopover);
this.map.on("pointermove", function (evt) {
var hit = this.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
return true;
});
if (hit) {
this.getTargetElement().style.cursor = 'pointer';
} else {
this.getTargetElement().style.cursor = '';
}
});
}
addControl(control) {
this.controls.push(control);
if (this.map) {
this.map.addControl(control);
}
}
addLayer(layer, type = 'static', to = "end") {
if (to === "end") this.layers[type].push(layer);
else if (to === "start") this.layers[type].unshift(layer)
if (this.map) {
const group = this.map.getLayers().getArray().find(g => g.get('type') === type);
if (group) {
if (to === "end") group.getLayers().getArray().push(layer);
else if (to === "start") group.getLayers().getArray().unshift(layer);
}
}
}
}