Browse Source

Map widget: improved marker, label and shape performance under frequent data updates and fixed outdated marker icons (#16758)

* Fix case when old marker override new one

* Extend fix

* Multiple perfomances fixes + fix zoom bug

* Map update only the items whose data changed

* Minor update

* Bug fixes and improvements

* Additional improvements

* Add improvements and fixes

* Fixes after review

* Cleanup

* Merge fix
fix/maps-performance
Kalytka Eugene 4 days ago
committed by GitHub
parent
commit
e7ea89ca86
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 36
      ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/circles-data-layer.ts
  2. 55
      ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/data-layer-utils.ts
  3. 83
      ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/latest-map-data-layer.ts
  4. 97
      ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/map-data-layer.ts
  5. 289
      ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/markers-data-layer.ts
  6. 56
      ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/polygons-data-layer.ts
  7. 59
      ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/polylines-data-layer.ts
  8. 18
      ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/shapes-data-layer.ts
  9. 154
      ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/trips-data-layer.ts
  10. 88
      ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts
  11. 3
      ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts
  12. 17
      ui-ngx/src/app/modules/home/components/widget/lib/maps/map.ts
  13. 83
      ui-ngx/src/app/shared/models/widget/maps/map.models.ts
  14. 1
      ui-ngx/src/typings/leaflet-extend-tb.d.ts

36
ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/circles-data-layer.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { import {
CirclesDataLayerSettings, CirclesDataLayerSettings,
defaultBaseCirclesDataLayerSettings, defaultBaseCirclesDataLayerSettings,
@ -9,9 +10,9 @@ import {
} from '@shared/models/widget/maps/map.models'; } from '@shared/models/widget/maps/map.models';
import L from 'leaflet'; import L from 'leaflet';
import { DataKey, FormattedData } from '@shared/models/widget.models'; import { DataKey, FormattedData } from '@shared/models/widget.models';
import { ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer'; import { isSameShapeStyle, ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer';
import { TbMap } from '@home/components/widget/lib/maps/map'; import { TbMap } from '@home/components/widget/lib/maps/map';
import { Observable } from 'rxjs'; import { Observable, Subscription } from 'rxjs';
import { isNotEmptyStr } from '@core/utils'; import { isNotEmptyStr } from '@core/utils';
import { import {
TbLatestDataLayerItem, TbLatestDataLayerItem,
@ -23,6 +24,8 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
private circle: L.Circle; private circle: L.Circle;
private circleStyleInfo: ShapeStyleInfo; private circleStyleInfo: ShapeStyleInfo;
private styleSubscription: Subscription;
private geometryDirty = false;
private editing = false; private editing = false;
constructor(data: FormattedData<TbMapDatasource>, constructor(data: FormattedData<TbMapDatasource>,
@ -41,6 +44,7 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
} }
public remove() { public remove() {
this.styleSubscription?.unsubscribe();
super.remove(); super.remove();
if (this.circleStyleInfo?.patternId) { if (this.circleStyleInfo?.patternId) {
this.dataLayer.getMap().unUseShapePattern(this.circleStyleInfo.patternId); this.dataLayer.getMap().unUseShapePattern(this.circleStyleInfo.patternId);
@ -56,7 +60,7 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
snapIgnore: !this.dataLayer.isSnappable() snapIgnore: !this.dataLayer.isSnappable()
}); });
this.dataLayer.getShapeStyle(data, dsData, this.circleStyleInfo?.patternId).subscribe((styleInfo) => { this.styleSubscription = this.dataLayer.getShapeStyle(data, dsData, this.circleStyleInfo?.patternId).subscribe((styleInfo) => {
this.circleStyleInfo = styleInfo; this.circleStyleInfo = styleInfo;
if (this.circle) { if (this.circle) {
this.circle.setStyle(this.circleStyleInfo.style); this.circle.setStyle(this.circleStyleInfo.style);
@ -77,12 +81,16 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
} }
protected doUpdate(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void { protected doUpdate(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void {
this.dataLayer.getShapeStyle(data, dsData, this.circleStyleInfo?.patternId).subscribe((styleInfo) => { this.styleSubscription?.unsubscribe();
this.styleSubscription = this.dataLayer.getShapeStyle(data, dsData, this.circleStyleInfo?.patternId).subscribe((styleInfo) => {
const styleChanged = !isSameShapeStyle(this.circleStyleInfo, styleInfo);
this.circleStyleInfo = styleInfo; this.circleStyleInfo = styleInfo;
this.updateCircleShape(data); const geometryChanged = this.updateCircleShape(data);
this.updateTooltip(data, dsData); this.updateTooltip(data, dsData);
this.updateLabel(data, dsData); this.updateLabel(data, dsData, geometryChanged);
this.circle.setStyle(this.circleStyleInfo.style); if (styleChanged) {
this.circle.setStyle(this.circleStyleInfo.style);
}
}); });
} }
@ -154,20 +162,28 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
const center = this.circle.getLatLng(); const center = this.circle.getLatLng();
const radius = this.circle.getRadius(); const radius = this.circle.getRadius();
this.dataLayer.saveCircleCoordinates(this.data, center, radius).subscribe(); this.dataLayer.saveCircleCoordinates(this.data, center, radius).subscribe();
this.geometryDirty = true;
this.markDataStale();
} }
private updateCircleShape(data: FormattedData<TbMapDatasource>) { private updateCircleShape(data: FormattedData<TbMapDatasource>): boolean {
if (this.editing) { if (this.editing) {
return; this.markDataStale();
return false;
} }
let changed = this.geometryDirty;
this.geometryDirty = false;
const circleData = this.dataLayer.extractCircleCoordinates(data); const circleData = this.dataLayer.extractCircleCoordinates(data);
const center = new L.LatLng(circleData.latitude, circleData.longitude); const center = new L.LatLng(circleData.latitude, circleData.longitude);
if (!this.circle.getLatLng().equals(center)) { if (!this.circle.getLatLng().equals(center)) {
this.circle.setLatLng(center); this.circle.setLatLng(center);
changed = true;
} }
if (this.circle.getRadius() !== circleData.radius) { if (this.circle.getRadius() !== circleData.radius) {
this.circle.setRadius(circleData.radius); this.circle.setRadius(circleData.radius);
changed = true;
} }
return changed;
} }
} }

55
ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/data-layer-utils.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { import {
DataLayerTooltipSettings, DataLayerTooltipSettings,
DataLayerTooltipTrigger, processTooltipTemplate, DataLayerTooltipTrigger, processTooltipTemplate,
@ -10,6 +11,14 @@ import { FormattedData } from '@shared/models/widget.models';
import L from 'leaflet'; import L from 'leaflet';
import { DataLayerPatternProcessor } from '@home/components/widget/lib/maps/data-layer/map-data-layer'; import { DataLayerPatternProcessor } from '@home/components/widget/lib/maps/data-layer/map-data-layer';
interface TooltipState {
processor: DataLayerPatternProcessor;
data: FormattedData<TbMapDatasource>;
content?: string;
}
const tooltipStates = new WeakMap<L.Popup, TooltipState>();
export const createTooltip = (map: TbMap<any>, export const createTooltip = (map: TbMap<any>,
layer: L.Layer, layer: L.Layer,
settings: DataLayerTooltipSettings, settings: DataLayerTooltipSettings,
@ -17,6 +26,13 @@ export const createTooltip = (map: TbMap<any>,
canOpen: () => boolean): L.Popup => { canOpen: () => boolean): L.Popup => {
const tooltip = L.popup({autoClose: settings.autoclose, closeOnClick: false}); const tooltip = L.popup({autoClose: settings.autoclose, closeOnClick: false});
(tooltip as any)._source = layer; (tooltip as any)._source = layer;
const open = (beforeOpen?: () => void) => {
if ((tooltip as any)._prepareOpen((layer as any)._latlng)) {
beforeOpen?.();
renderTooltip(tooltip, map.getData());
tooltip.openOn(map.getMap());
}
};
layer.on('move', (e) => { layer.on('move', (e) => {
tooltip.setLatLng((e as any).latlng); tooltip.setLatLng((e as any).latlng);
}); });
@ -29,18 +45,13 @@ export const createTooltip = (map: TbMap<any>,
if (tooltip.isOpen()) { if (tooltip.isOpen()) {
tooltip.close(); tooltip.close();
} else if (canOpen()) { } else if (canOpen()) {
if ((tooltip as any)._prepareOpen((layer as any)._latlng)) { open(() => map.deselectItem());
map.deselectItem();
tooltip.openOn(map.getMap());
}
} }
}); });
} else if (settings.trigger === DataLayerTooltipTrigger.hover) { } else if (settings.trigger === DataLayerTooltipTrigger.hover) {
layer.on('mouseover', () => { layer.on('mouseover', () => {
if (canOpen()) { if (canOpen()) {
if ((tooltip as any)._prepareOpen((layer as any)._latlng)) { open();
tooltip.openOn(map.getMap());
}
} }
}); });
layer.on('mousemove', (e) => { layer.on('mousemove', (e) => {
@ -51,7 +62,7 @@ export const createTooltip = (map: TbMap<any>,
}); });
} }
layer.on('popupopen', () => { layer.on('popupopen', () => {
bindTooltipActions(map, tooltip, settings, data); bindTooltipActions(map, tooltip, settings, tooltipStates.get(tooltip)?.data ?? data);
}); });
return tooltip; return tooltip;
} }
@ -62,12 +73,26 @@ export const updateTooltip = (map: TbMap<any>,
processor: DataLayerPatternProcessor, processor: DataLayerPatternProcessor,
data: FormattedData<TbMapDatasource>, data: FormattedData<TbMapDatasource>,
dsData: FormattedData<TbMapDatasource>[]): void => { dsData: FormattedData<TbMapDatasource>[]): void => {
let tooltipTemplate = processor.processPattern(data, dsData); tooltipStates.set(tooltip, {processor, data, content: tooltipStates.get(tooltip)?.content});
tooltipTemplate = processTooltipTemplate(tooltipTemplate); if (tooltip.isOpen()) {
tooltip.setContent(tooltipTemplate); if (renderTooltip(tooltip, dsData) && tooltip.getElement()) {
if (tooltip.isOpen() && tooltip.getElement()) { bindTooltipActions(map, tooltip, settings, data);
bindTooltipActions(map, tooltip, settings, data); }
}
}
const renderTooltip = (tooltip: L.Popup, dsData: FormattedData<TbMapDatasource>[]): boolean => {
const state = tooltipStates.get(tooltip);
let changed = false;
if (state) {
const content = processTooltipTemplate(state.processor.processPattern(state.data, dsData));
if (content !== state.content) {
state.content = content;
tooltip.setContent(content);
changed = true;
}
} }
return changed;
} }
const bindTooltipActions = (map: TbMap<any>, tooltip: L.Popup, settings: DataLayerTooltipSettings, data: FormattedData<TbMapDatasource>): void => { const bindTooltipActions = (map: TbMap<any>, tooltip: L.Popup, settings: DataLayerTooltipSettings, data: FormattedData<TbMapDatasource>): void => {
@ -80,7 +105,7 @@ const bindTooltipActions = (map: TbMap<any>, tooltip: L.Popup, settings: DataLay
if (action) { if (action) {
element.onclick = ($event) => element.onclick = ($event) =>
{ {
map.dataItemClick($event, action, data); map.dataItemClick($event, action, tooltipStates.get(tooltip)?.data ?? data);
return false; return false;
}; };
} }

83
ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/latest-map-data-layer.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { import {
DataLayerEditAction, DataLayerEditAction,
MapDataLayerSettings, MapDataLayerSettings,
@ -12,12 +13,25 @@ import L from 'leaflet';
import { createTooltip, updateTooltip } from './data-layer-utils'; import { createTooltip, updateTooltip } from './data-layer-utils';
import { TbDataLayerItem, TbMapDataLayer } from '@home/components/widget/lib/maps/data-layer/map-data-layer'; import { TbDataLayerItem, TbMapDataLayer } from '@home/components/widget/lib/maps/data-layer/map-data-layer';
const isSameFormattedData = (a: FormattedData<TbMapDatasource>, b: FormattedData<TbMapDatasource>): boolean => {
if (a === b) {
return true;
}
if (!a || !b) {
return false;
}
const aKeys = Object.keys(a);
return aKeys.length === Object.keys(b).length && aKeys.every(key => a[key] === b[key]);
};
export abstract class TbLatestDataLayerItem<S extends MapDataLayerSettings = MapDataLayerSettings, export abstract class TbLatestDataLayerItem<S extends MapDataLayerSettings = MapDataLayerSettings,
D extends TbLatestMapDataLayer<S,D> = TbLatestMapDataLayer<any>, L extends L.Layer = L.Layer> extends TbDataLayerItem<S,D,L> { D extends TbLatestMapDataLayer<S,D> = TbLatestMapDataLayer<any>, L extends L.Layer = L.Layer> extends TbDataLayerItem<S,D,L> {
protected tooltip: L.Popup; protected tooltip: L.Popup;
protected labelContent: string;
protected data: FormattedData<TbMapDatasource>; protected data: FormattedData<TbMapDatasource>;
protected selected = false; protected selected = false;
private dataStale = false;
protected constructor(data: FormattedData<TbMapDatasource>, protected constructor(data: FormattedData<TbMapDatasource>,
dsData: FormattedData<TbMapDatasource>[], dsData: FormattedData<TbMapDatasource>[],
@ -35,8 +49,10 @@ export abstract class TbLatestDataLayerItem<S extends MapDataLayerSettings = Map
this.settings.tooltip, this.dataLayer.dataLayerTooltipProcessor, data, dsData); this.settings.tooltip, this.dataLayer.dataLayerTooltipProcessor, data, dsData);
} }
this.bindEvents(); this.bindEvents();
}
public onAddedToContainer(): void {
try { try {
this.dataLayer.getDataLayerContainer().addLayer(this.layer);
this.editModeUpdated(); this.editModeUpdated();
} catch (e) { } catch (e) {
console.warn(e); console.warn(e);
@ -113,9 +129,15 @@ export abstract class TbLatestDataLayerItem<S extends MapDataLayerSettings = Map
} }
} }
public update(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void { public update(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): boolean {
this.data = data; if (!this.dataStale && this.dataLayer.canSkipUnchangedItems() && isSameFormattedData(this.data, data)) {
this.doUpdate(data, dsData); return false;
} else {
this.dataStale = false;
this.data = data;
this.doUpdate(data, dsData);
return true;
}
} }
public remove() { public remove() {
@ -130,6 +152,15 @@ export abstract class TbLatestDataLayerItem<S extends MapDataLayerSettings = Map
return false; return false;
} }
protected markDataStale(): void {
this.dataStale = true;
}
protected reapplyData(): void {
this.dataStale = false;
this.doUpdate(this.data, this.dataLayer.getMap().getData());
}
protected bindEvents(): void { protected bindEvents(): void {
if (this.dataLayer.isSelectable()) { if (this.dataLayer.isSelectable()) {
this.layer.on('click', () => { this.layer.on('click', () => {
@ -182,16 +213,23 @@ export abstract class TbLatestDataLayerItem<S extends MapDataLayerSettings = Map
} }
} }
protected updateLabel(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) { protected updateLabel(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[], force = true) {
if (this.settings.label.show) { if (this.settings.label.show) {
this.unbindLabel(); const content = this.createLabelContent(data, dsData);
const label = this.dataLayer.dataLayerLabelProcessor.processPattern(data, dsData); if (force || content !== this.labelContent) {
const labelColor = this.dataLayer.getCtx().widgetConfig.color; this.unbindLabel();
const content: L.Content = `<div style="color: ${labelColor};"><b>${label}</b></div>`; this.bindLabel(content);
this.bindLabel(content); this.labelContent = content;
}
} }
} }
protected createLabelContent(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): string {
const label = this.dataLayer.dataLayerLabelProcessor.processPattern(data, dsData);
const labelColor = this.dataLayer.getCtx().widgetConfig.color;
return `<div style="color: ${labelColor};"><b>${label}</b></div>`;
}
protected canDeselect(cancel = false): boolean { protected canDeselect(cancel = false): boolean {
return true; return true;
} }
@ -311,15 +349,18 @@ export abstract class TbLatestMapDataLayer<S extends MapDataLayerSettings = MapD
const layerData = dsData.filter(d => d.$datasource.mapDataIds.includes(this.mapDataId)); const layerData = dsData.filter(d => d.$datasource.mapDataIds.includes(this.mapDataId));
const toDelete = new Set(Array.from(this.layerItems.keys())); const toDelete = new Set(Array.from(this.layerItems.keys()));
const updatedItems: TbLatestDataLayerItem<S,D,L>[] = []; const updatedItems: TbLatestDataLayerItem<S,D,L>[] = [];
const createdItems: TbLatestDataLayerItem<S,D,L>[] = [];
layerData.forEach((data) => { layerData.forEach((data) => {
if (this.isValidLayerData(data)) { if (this.isValidLayerData(data)) {
let layerItem = this.layerItems.get(data.entityId); let layerItem = this.layerItems.get(data.entityId);
if (layerItem) { if (layerItem) {
layerItem.update(data, dsData); if (layerItem.update(data, dsData)) {
updatedItems.push(layerItem); updatedItems.push(layerItem);
}
} else { } else {
layerItem = this.createLayerItem(data, dsData); layerItem = this.createLayerItem(data, dsData);
this.layerItems.set(data.entityId, layerItem); this.layerItems.set(data.entityId, layerItem);
createdItems.push(layerItem);
} }
toDelete.delete(data.entityId); toDelete.delete(data.entityId);
} else { } else {
@ -332,6 +373,9 @@ export abstract class TbLatestMapDataLayer<S extends MapDataLayerSettings = MapD
toDelete.forEach((key) => { toDelete.forEach((key) => {
this.removeItem(key); this.removeItem(key);
}); });
if (createdItems.length) {
this.addItemsToContainer(createdItems);
}
if (updatedItems.length) { if (updatedItems.length) {
this.layerItemsUpdated(updatedItems); this.layerItemsUpdated(updatedItems);
} }
@ -388,6 +432,7 @@ export abstract class TbLatestMapDataLayer<S extends MapDataLayerSettings = MapD
this.unplacedItems.splice(index, 1); this.unplacedItems.splice(index, 1);
const layerItem = this.createLayerItem(unplacedItem.entity, this.map.getData()); const layerItem = this.createLayerItem(unplacedItem.entity, this.map.getData());
this.layerItems.set(unplacedItem.entity.entityId, layerItem); this.layerItems.set(unplacedItem.entity.entityId, layerItem);
this.addItemsToContainer([layerItem]);
this.map.enabledDataLayersUpdated(); this.map.enabledDataLayersUpdated();
} }
} }
@ -395,6 +440,18 @@ export abstract class TbLatestMapDataLayer<S extends MapDataLayerSettings = MapD
protected layerItemsUpdated(_updatedItems: TbLatestDataLayerItem<S,D,L>[]): void { protected layerItemsUpdated(_updatedItems: TbLatestDataLayerItem<S,D,L>[]): void {
} }
protected addItemsToContainer(items: TbLatestDataLayerItem<S,D,L>[]): void {
const container = this.getDataLayerContainer();
for (const item of items) {
try {
container.addLayer(item.getLayer());
} catch (e) {
console.warn(e);
}
}
items.forEach(item => item.onAddedToContainer());
}
private prepareUnplacedItems(): UnplacedMapDataItem[] { private prepareUnplacedItems(): UnplacedMapDataItem[] {
const div = document.createElement('div'); const div = document.createElement('div');
for (const item of this.unplacedItems) { for (const item of this.unplacedItems) {

97
ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/map-data-layer.ts

@ -14,7 +14,7 @@ import {
TbMapDatasource TbMapDatasource
} from '@shared/models/widget/maps/map.models'; } from '@shared/models/widget/maps/map.models';
import { import {
createLabelFromPattern, fillDataPattern,
guid, guid,
isDefined, isDefined,
isDefinedAndNotNull, isDefinedAndNotNull,
@ -28,21 +28,79 @@ import L from 'leaflet';
import { CompiledTbFunction } from '@shared/models/js-function.models'; import { CompiledTbFunction } from '@shared/models/js-function.models';
import { forkJoin, Observable, of } from 'rxjs'; import { forkJoin, Observable, of } from 'rxjs';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { DataKey, DatasourceType, FormattedData } from '@shared/models/widget.models'; import { DataKey, DatasourceType, FormattedData, ReplaceInfo } from '@shared/models/widget.models';
import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe'; import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe';
import { TbMap } from '@home/components/widget/lib/maps/map'; import { TbMap } from '@home/components/widget/lib/maps/map';
import { WidgetContext } from '@home/models/widget-component.models'; import { WidgetContext } from '@home/models/widget-component.models';
import { ColorRange } from '@shared/models/widget-settings.models'; import { ColorRange } from '@shared/models/widget-settings.models';
const additionalDataArgsRegex = /\b(dsData|ctx|arguments|Date|moment|performance)\b/;
export const tbFunctionUsesAdditionalData = (value: any): boolean => {
const body = typeof value === 'string' ? value : value?.body;
const hasModules = !!value?.modules && Object.keys(value.modules).length > 0;
return typeof body === 'string' && (hasModules || additionalDataArgsRegex.test(body));
};
const settingsUseAdditionalData = (value: any, key?: string): boolean => {
if (key?.endsWith('Function')) {
return tbFunctionUsesAdditionalData(value);
}
if (value && typeof value === 'object') {
return Object.keys(value).some(k => settingsUseAdditionalData(value[k], k));
}
return false;
};
interface ParsedPatternVariable {
variable: string;
label: string;
valDec: number;
keyIndex?: number;
}
const patternVariableRegex = /\${([^}]*)}/g;
const parsePatternVariables = (pattern: string): ParsedPatternVariable[] => {
const variables: ParsedPatternVariable[] = [];
if (typeof pattern === 'string') {
for (const match of pattern.matchAll(patternVariableRegex)) {
let label = match[1];
let valDec = 2;
const splitValues = label.split(':');
if (splitValues.length > 1) {
label = splitValues[0];
valDec = parseFloat(splitValues[1]);
}
const variable: ParsedPatternVariable = {variable: match[0], label, valDec};
if (label.startsWith('#')) {
const keyIndexStr = label.substring(1);
const n = Math.floor(Number(keyIndexStr));
variable.label = '';
if (String(n) === keyIndexStr && n >= 0) {
variable.keyIndex = n;
}
}
variables.push(variable);
}
}
return variables;
};
export class DataLayerPatternProcessor { export class DataLayerPatternProcessor {
private static readonly PARSED_PATTERN_CACHE_SIZE = 100;
private patternFunction: CompiledTbFunction<MapStringFunction>; private patternFunction: CompiledTbFunction<MapStringFunction>;
private pattern: string; private pattern: string;
private customTranslate: CustomTranslatePipe;
private parsedPatterns = new Map<string, ParsedPatternVariable[]>();
constructor(private dataLayer: TbMapDataLayer, constructor(private dataLayer: TbMapDataLayer,
private settings: DataLayerPatternSettings) {} private settings: DataLayerPatternSettings) {}
public setup(): Observable<void> { public setup(): Observable<void> {
this.customTranslate = this.dataLayer.getCtx().$injector.get(CustomTranslatePipe);
if (this.settings.type === DataLayerPatternType.function) { if (this.settings.type === DataLayerPatternType.function) {
return parseTbFunction<MapStringFunction>(this.dataLayer.getCtx().http, this.settings.patternFunction, ['data', 'dsData', 'ctx']).pipe( return parseTbFunction<MapStringFunction>(this.dataLayer.getCtx().http, this.settings.patternFunction, ['data', 'dsData', 'ctx']).pipe(
map((parsed) => { map((parsed) => {
@ -63,9 +121,31 @@ export class DataLayerPatternProcessor {
} else { } else {
pattern = this.pattern; pattern = this.pattern;
} }
const text = createLabelFromPattern(pattern, data); const replaceInfo: ReplaceInfo[] = [];
const customTranslate = this.dataLayer.getCtx().$injector.get(CustomTranslatePipe); for (const v of this.getParsedPattern(pattern)) {
return customTranslate.transform(text); let dataKeyName = v.label;
if (v.keyIndex !== undefined) {
const dataKey = data.$datasource?.dataKeys?.[v.keyIndex];
if (!dataKey) {
break;
}
dataKeyName = dataKey.label;
}
replaceInfo.push({variable: v.variable, valDec: v.valDec, dataKeyName});
}
return this.customTranslate.transform(fillDataPattern(pattern, replaceInfo, data));
}
private getParsedPattern(pattern: string): ParsedPatternVariable[] {
let parsed = this.parsedPatterns.get(pattern);
if (!parsed) {
parsed = parsePatternVariables(pattern);
if (this.parsedPatterns.size >= DataLayerPatternProcessor.PARSED_PATTERN_CACHE_SIZE) {
this.parsedPatterns.delete(this.parsedPatterns.keys().next().value);
}
this.parsedPatterns.set(pattern, parsed);
}
return parsed;
} }
} }
@ -171,12 +251,15 @@ export abstract class TbMapDataLayer<S extends MapDataLayerSettings = MapDataLay
protected snappable = false; protected snappable = false;
protected itemsUseAdditionalData: boolean;
public dataLayerLabelProcessor: DataLayerPatternProcessor; public dataLayerLabelProcessor: DataLayerPatternProcessor;
public dataLayerTooltipProcessor: DataLayerPatternProcessor; public dataLayerTooltipProcessor: DataLayerPatternProcessor;
protected constructor(protected map: TbMap<any>, protected constructor(protected map: TbMap<any>,
inputSettings: S) { inputSettings: S) {
this.settings = mergeDeepIgnoreArray({} as S, this.defaultBaseSettings(map) as S, inputSettings); this.settings = mergeDeepIgnoreArray({} as S, this.defaultBaseSettings(map) as S, inputSettings);
this.itemsUseAdditionalData = settingsUseAdditionalData(this.settings);
if (this.settings.groups?.length) { if (this.settings.groups?.length) {
this.settings.groups.forEach((group) => { this.settings.groups.forEach((group) => {
this.groupsState[group] = true; this.groupsState[group] = true;
@ -222,6 +305,10 @@ export abstract class TbMapDataLayer<S extends MapDataLayerSettings = MapDataLay
this.layerItems.forEach(item => item.invalidateCoordinates()); this.layerItems.forEach(item => item.invalidateCoordinates());
} }
public canSkipUnchangedItems(): boolean {
return !this.itemsUseAdditionalData;
}
public getCtx(): WidgetContext { public getCtx(): WidgetContext {
return this.map.getCtx(); return this.map.getCtx();
} }

289
ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/markers-data-layer.ts

@ -25,17 +25,18 @@ import {
} from '@shared/models/widget/maps/map.models'; } from '@shared/models/widget/maps/map.models';
import L, { FeatureGroup } from 'leaflet'; import L, { FeatureGroup } from 'leaflet';
import { DataKey, FormattedData } from '@shared/models/widget.models'; import { DataKey, FormattedData } from '@shared/models/widget.models';
import { forkJoin, Observable, of } from 'rxjs'; import { forkJoin, Observable, of, Subscription, throwError } from 'rxjs';
import { CompiledTbFunction } from '@shared/models/js-function.models'; import { CompiledTbFunction } from '@shared/models/js-function.models';
import { import {
deepClone, deepClone,
isDefined, isDefined,
isDefinedAndNotNull, isDefinedAndNotNull,
isEmptyStr, isEmptyStr,
isEqual,
parseTbFunction, plainColorFromVariable, parseTbFunction, plainColorFromVariable,
safeExecuteTbFunction safeExecuteTbFunction
} from '@core/utils'; } from '@core/utils';
import { catchError, map, switchMap } from 'rxjs/operators'; import { catchError, map, shareReplay, switchMap } from 'rxjs/operators';
import tinycolor from 'tinycolor2'; import tinycolor from 'tinycolor2';
import { ImagePipe } from '@shared/pipe/image.pipe'; import { ImagePipe } from '@shared/pipe/image.pipe';
import { TbMap } from '@home/components/widget/lib/maps/map'; import { TbMap } from '@home/components/widget/lib/maps/map';
@ -57,8 +58,12 @@ import { DataLayerColorProcessor, TbMapDataLayer } from '@home/components/widget
export class MarkerDataProcessor<S extends MarkersDataLayerSettings = MarkersDataLayerSettings> { export class MarkerDataProcessor<S extends MarkersDataLayerSettings = MarkersDataLayerSettings> {
private static readonly MARKER_ICON_CACHE_SIZE = 256;
private positionFunction: CompiledTbFunction<MarkerPositionFunction>; private positionFunction: CompiledTbFunction<MarkerPositionFunction>;
private markerIconProcessor: MarkerIconProcessor<any>; private markerIconProcessor: MarkerIconProcessor<any>;
private markerIconCache = new Map<string, MarkerIconInfo>();
private markerAssetCache = new Map<string, Observable<unknown>>();
constructor(public dataLayer: TbMapDataLayer, constructor(public dataLayer: TbMapDataLayer,
private settings: S, private settings: S,
@ -129,54 +134,116 @@ export class MarkerDataProcessor<S extends MarkersDataLayerSettings = MarkersDat
} }
public createColoredMarkerShape(shape: MarkerShape, color: tinycolor.Instance, rotationAngle = 0, size = 34): Observable<MarkerIconInfo> { public createColoredMarkerShape(shape: MarkerShape, color: tinycolor.Instance, rotationAngle = 0, size = 34): Observable<MarkerIconInfo> {
return createColorMarkerShapeURI(this.dataLayer.getCtx().$injector.get(MatIconRegistry), this.dataLayer.getCtx().$injector.get(DomSanitizer), shape, color).pipe( const assetKey = `shape|${shape}|${color.toHex8()}`;
map((iconUrl) => { return this.cachedMarkerIcon(assetKey, rotationAngle, size,
let icon: L.Icon<L.BaseIconOptions>; () => createColorMarkerShapeURI(this.dataLayer.getCtx().$injector.get(MatIconRegistry),
if (rotationAngle === 0) { this.dataLayer.getCtx().$injector.get(DomSanitizer), shape, color),
icon = L.icon({ (iconUrl: string) => this.buildColoredMarkerShape(iconUrl, rotationAngle, size));
iconUrl,
iconSize: [size, size],
iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]],
popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]]
});
} else {
const style = `background-image: url(${iconUrl}); transform: rotate(${rotationAngle}deg); height: ${size}px; width: ${size}px;`;
icon = L.divIcon({
html: `<div style="${style}"></div>`,
className: 'tb-marker-div-icon',
iconSize: [size, size],
iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]],
popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]]
});
}
return {
size: [size, size],
icon
}
})
);
} }
public createColoredMarkerIcon(iconContainer: MarkerIconContainer, public createColoredMarkerIcon(iconContainer: MarkerIconContainer,
icon: string, color: tinycolor.Instance, rotationAngle = 0, size = 34): Observable<MarkerIconInfo> { icon: string, color: tinycolor.Instance, rotationAngle = 0, size = 34): Observable<MarkerIconInfo> {
return createColorMarkerIconElement(this.dataLayer.getCtx().$injector.get(MatIconRegistry), this.dataLayer.getCtx().$injector.get(DomSanitizer), const assetKey = `icon|${iconContainer}|${icon}|${color.toHex8()}`;
iconContainer, icon, color).pipe( return this.cachedMarkerIcon(assetKey, rotationAngle, size,
map((element) => { () => createColorMarkerIconElement(this.dataLayer.getCtx().$injector.get(MatIconRegistry),
if (rotationAngle !== 0) { this.dataLayer.getCtx().$injector.get(DomSanitizer), iconContainer, icon, color),
element.style.transform = `rotate(${rotationAngle}deg)`; (element: SVGElement) => this.buildColoredMarkerIcon(element, rotationAngle, size));
} }
return {
size: [size, size], private cachedMarkerIcon<T>(assetKey: string, rotationAngle: number, size: number,
icon: L.divIcon({ loadAsset: () => Observable<T>,
html: element.outerHTML, buildIcon: (asset: T) => MarkerIconInfo): Observable<MarkerIconInfo> {
className: 'tb-marker-div-icon', const iconKey = `${assetKey}|${size}`;
iconSize: [size, size], const cachedIcon = rotationAngle === 0 ? this.lruGet(this.markerIconCache, iconKey) : undefined;
iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]], let result: Observable<MarkerIconInfo>;
popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]] if (cachedIcon) {
}) result = of(cachedIcon);
}; } else {
let asset$ = this.lruGet(this.markerAssetCache, assetKey) as Observable<T>;
if (!asset$) {
const shared$: Observable<T> = loadAsset().pipe(
catchError((error) => {
if (this.markerAssetCache.get(assetKey) === shared$) {
this.markerAssetCache.delete(assetKey);
}
return throwError(() => error);
}),
shareReplay({bufferSize: 1, refCount: false})
);
this.lruSet(this.markerAssetCache, assetKey, shared$);
asset$ = shared$;
}
result = asset$.pipe(
map((asset) => {
const iconInfo = buildIcon(asset);
if (rotationAngle === 0) {
this.lruSet(this.markerIconCache, iconKey, iconInfo);
}
return iconInfo;
})
);
}
return result;
}
private lruGet<V>(cache: Map<string, V>, key: string): V | undefined {
const value = cache.get(key);
if (value !== undefined) {
cache.delete(key);
cache.set(key, value);
}
return value;
}
private lruSet<V>(cache: Map<string, V>, key: string, value: V) {
cache.set(key, value);
if (cache.size > MarkerDataProcessor.MARKER_ICON_CACHE_SIZE) {
cache.delete(cache.keys().next().value);
}
}
private buildColoredMarkerShape(iconUrl: string, rotationAngle: number, size: number): MarkerIconInfo {
let icon: L.Icon<L.BaseIconOptions>;
if (rotationAngle === 0) {
icon = L.icon({
iconUrl,
iconSize: [size, size],
iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]],
popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]]
});
} else {
const style = `background-image: url(${iconUrl}); transform: rotate(${rotationAngle}deg); height: ${size}px; width: ${size}px;`;
icon = L.divIcon({
html: `<div style="${style}"></div>`,
className: 'tb-marker-div-icon',
iconSize: [size, size],
iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]],
popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]]
});
}
return {
size: [size, size],
icon
};
}
private buildColoredMarkerIcon(sourceElement: SVGElement, rotationAngle: number, size: number): MarkerIconInfo {
let html = sourceElement.outerHTML;
if (rotationAngle !== 0) {
const element = sourceElement.cloneNode(true) as SVGElement;
element.style.transform = `rotate(${rotationAngle}deg)`;
html = element.outerHTML;
}
return {
size: [size, size],
icon: L.divIcon({
html,
className: 'tb-marker-div-icon',
iconSize: [size, size],
iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]],
popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]]
}) })
); };
} }
} }
@ -377,12 +444,33 @@ class ImageMarkerIconProcessor extends MarkerIconProcessor<MarkerImageSettings>
} }
} }
export const createPlaceholderMarkerIcon = (): L.DivIcon =>
L.divIcon({ html: '', className: 'tb-marker-div-icon', iconSize: [0, 0] });
export const isSameMarkerIcon = (applied: MarkerIconInfo, next: MarkerIconInfo): boolean =>
!!applied && (applied === next || (
applied.icon.constructor === next.icon.constructor &&
isEqual(applied.size, next.size) &&
isEqual(applied.icon.options, next.icon.options)
));
const rotationFreeIconOptions = (options: L.DivIconOptions): L.DivIconOptions =>
typeof options.html === 'string' ? {...options, html: options.html.replace(/rotate\([^)]*\)/, 'rotate()')} : options;
export const isRotationOnlyIconChange = (applied: MarkerIconInfo, next: MarkerIconInfo): boolean =>
!!applied && applied.icon instanceof L.DivIcon && next.icon instanceof L.DivIcon &&
isEqual(applied.size, next.size) &&
isEqual(rotationFreeIconOptions(applied.icon.options), rotationFreeIconOptions(next.icon.options));
class TbMarkerDataLayerItem extends TbLatestDataLayerItem<MarkersDataLayerSettings, TbMarkersDataLayer, L.Marker> { class TbMarkerDataLayerItem extends TbLatestDataLayerItem<MarkersDataLayerSettings, TbMarkersDataLayer, L.Marker> {
private marker: L.Marker; private marker: L.Marker;
private labelOffset: L.PointTuple; private labelOffset: L.PointTuple;
private boundLabelOffset: L.PointTuple;
private appliedIconInfo: MarkerIconInfo;
private iconClassList: string[]; private iconClassList: string[];
private moving = false; private moving = false;
private markerIconSubscription: Subscription;
private dragStart: () => void; private dragStart: () => void;
private dragEnd: () => void; private dragEnd: () => void;
@ -401,12 +489,18 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem<MarkersDataLayerSettin
this.marker.options.bubblingMouseEvents = !this.dataLayer.isEditMode(); this.marker.options.bubblingMouseEvents = !this.dataLayer.isEditMode();
} }
public remove() {
this.markerIconSubscription?.unsubscribe();
super.remove();
}
protected create(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): L.Marker { protected create(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): L.Marker {
this.iconClassList = []; this.iconClassList = [];
const location = this.dataLayer.dataProcessor.extractLocation(data, dsData); const location = this.dataLayer.dataProcessor.extractLocation(data, dsData);
this.dragStart = this._dragStart.bind(this); this.dragStart = this._dragStart.bind(this);
this.dragEnd = this._dragEnd.bind(this); this.dragEnd = this._dragEnd.bind(this);
this.marker = L.marker(location, { this.marker = L.marker(location, {
icon: createPlaceholderMarkerIcon(),
tbMarkerData: data, tbMarkerData: data,
snapIgnore: !this.dataLayer.isSnappable(), snapIgnore: !this.dataLayer.isSnappable(),
bubblingMouseEvents: !this.dataLayer.isEditMode(), bubblingMouseEvents: !this.dataLayer.isEditMode(),
@ -424,6 +518,23 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem<MarkersDataLayerSettin
this.marker.bindTooltip(content, { className: 'tb-marker-label', permanent: true, direction: 'top', offset: this.labelOffset }); this.marker.bindTooltip(content, { className: 'tb-marker-label', permanent: true, direction: 'top', offset: this.labelOffset });
} }
protected updateLabel(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) {
if (this.settings.label.show) {
const content = this.createLabelContent(data, dsData);
const offsetChanged = !isEqual(this.boundLabelOffset, this.labelOffset);
if (this.marker.getTooltip() && !offsetChanged) {
if (content !== this.labelContent) {
this.marker.setTooltipContent(content);
}
} else {
this.unbindLabel();
this.bindLabel(content);
}
this.labelContent = content;
this.boundLabelOffset = this.labelOffset;
}
}
protected doUpdate(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void { protected doUpdate(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void {
this.marker.options.tbMarkerData = data; this.marker.options.tbMarkerData = data;
this.updateMarkerLocation(data, dsData); this.updateMarkerLocation(data, dsData);
@ -501,6 +612,7 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem<MarkersDataLayerSettin
private saveMarkerLocation() { private saveMarkerLocation() {
const location = this.marker.getLatLng(); const location = this.marker.getLatLng();
this.dataLayer.saveMarkerLocation(this.data, location).subscribe(); this.dataLayer.saveMarkerLocation(this.data, location).subscribe();
this.markDataStale();
} }
private updateMarkerLocation(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) { private updateMarkerLocation(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) {
@ -511,25 +623,29 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem<MarkersDataLayerSettin
} }
private updateMarkerIcon(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) { private updateMarkerIcon(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) {
this.dataLayer.dataProcessor.createMarkerIcon(data, dsData).subscribe( this.markerIconSubscription?.unsubscribe();
this.markerIconSubscription = this.dataLayer.dataProcessor.createMarkerIcon(data, dsData).subscribe(
(iconInfo) => { (iconInfo) => {
let icon: L.Icon | L.DivIcon; if (!isSameMarkerIcon(this.appliedIconInfo, iconInfo)) {
const options = deepClone(iconInfo.icon.options); let icon: L.Icon | L.DivIcon;
options.className = this.updateIconClasses(options.className); const options = deepClone(iconInfo.icon.options);
if (iconInfo.icon instanceof L.DivIcon) { options.className = this.updateIconClasses(options.className);
icon = L.divIcon(options); if (iconInfo.icon instanceof L.DivIcon) {
} else { icon = L.divIcon(options);
icon = L.icon(options as L.IconOptions); } else {
} icon = L.icon(options as L.IconOptions);
this.marker.setIcon(icon); }
const anchor = options.iconAnchor; this.marker.setIcon(icon);
if (anchor && Array.isArray(anchor)) { this.appliedIconInfo = iconInfo;
this.labelOffset = [iconInfo.size[0] / 2 - anchor[0], 10 - anchor[1]]; const anchor = options.iconAnchor;
} else { if (anchor && Array.isArray(anchor)) {
this.labelOffset = [0, -iconInfo.size[1] * this.dataLayer.markerOffset[1] + 10]; this.labelOffset = [iconInfo.size[0] / 2 - anchor[0], 10 - anchor[1]];
} else {
this.labelOffset = [0, -iconInfo.size[1] * this.dataLayer.markerOffset[1] + 10];
}
this.editModeUpdated();
} }
this.updateLabel(data, dsData); this.updateLabel(data, dsData);
this.editModeUpdated();
} }
); );
} }
@ -562,6 +678,8 @@ export class TbMarkersDataLayer extends TbLatestMapDataLayer<MarkersDataLayerSet
public tooltipOffset: L.LatLngTuple; public tooltipOffset: L.LatLngTuple;
private markersClusterContainer: L.MarkerClusterGroup; private markersClusterContainer: L.MarkerClusterGroup;
private pendingClusterLayers = new Set<L.Layer>();
private removedPendingClusterLayers = new Set<L.Layer>();
private clusterMarkerColorFunction: CompiledTbFunction<ClusterMarkerColorFunction>; private clusterMarkerColorFunction: CompiledTbFunction<ClusterMarkerColorFunction>;
private readonly markersPane: string; private readonly markersPane: string;
@ -679,6 +797,54 @@ export class TbMarkersDataLayer extends TbLatestMapDataLayer<MarkersDataLayerSet
super.layerItemsUpdated(updatedItems); super.layerItemsUpdated(updatedItems);
} }
public removeItem(key: string): void {
const layer = this.layerItems.get(key)?.getLayer();
if (layer && this.pendingClusterLayers.has(layer)) {
this.removedPendingClusterLayers.add(layer);
}
super.removeItem(key);
}
public getBounds(): L.LatLngBounds {
let bounds = super.getBounds();
if (this.pendingClusterLayers.size) {
const result = new L.LatLngBounds(null, null);
if (bounds.isValid()) {
result.extend(bounds);
}
this.pendingClusterLayers.forEach(layer => {
if (!this.removedPendingClusterLayers.has(layer)) {
result.extend((layer as L.Marker).getLatLng());
}
});
bounds = result;
}
return bounds;
}
protected addItemsToContainer(items: TbLatestDataLayerItem<MarkersDataLayerSettings, TbMarkersDataLayer, L.Marker>[]): void {
if (this.settings.markerClustering?.enable) {
const layers = items.map(item => item.getLayer());
if (this.settings.markerClustering.chunkedLoad && this.map.getMap().hasLayer(this.markersClusterContainer)) {
layers.forEach(layer => this.pendingClusterLayers.add(layer));
}
try {
this.markersClusterContainer.addLayers(layers);
} catch (e) {
console.warn(e);
}
items.forEach(item => item.onAddedToContainer());
} else {
super.addItemsToContainer(items);
}
}
private onClusterLayerAdded(layer: L.Layer) {
if (this.pendingClusterLayers.delete(layer) && this.removedPendingClusterLayers.delete(layer)) {
Promise.resolve().then(() => this.markersClusterContainer.removeLayer(layer));
}
}
private createMarkersClusterContainer(): L.FeatureGroup { private createMarkersClusterContainer(): L.FeatureGroup {
const markerClusterOptions: L.MarkerClusterGroupOptions = { const markerClusterOptions: L.MarkerClusterGroupOptions = {
spiderfyOnMaxZoom: this.settings.markerClustering?.spiderfyOnMaxZoom, spiderfyOnMaxZoom: this.settings.markerClustering?.spiderfyOnMaxZoom,
@ -729,6 +895,7 @@ export class TbMarkersDataLayer extends TbLatestMapDataLayer<MarkersDataLayerSet
markerClusterOptions.disableClusteringAtZoom = Math.floor(this.settings.markerClustering.maxZoom); markerClusterOptions.disableClusteringAtZoom = Math.floor(this.settings.markerClustering.maxZoom);
} }
this.markersClusterContainer = new L.MarkerClusterGroup(markerClusterOptions); this.markersClusterContainer = new L.MarkerClusterGroup(markerClusterOptions);
this.markersClusterContainer.on('layeradd', (e: L.LayerEvent) => this.onClusterLayerAdded(e.layer));
return this.markersClusterContainer; return this.markersClusterContainer;
} }

56
ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/polygons-data-layer.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { import {
defaultBasePolygonsDataLayerSettings, defaultBasePolygonsDataLayerSettings,
isCutPolygon, isJSON, MapDataLayerType, isCutPolygon, isJSON, MapDataLayerType,
@ -8,9 +9,9 @@ import {
} from '@shared/models/widget/maps/map.models'; } from '@shared/models/widget/maps/map.models';
import L from 'leaflet'; import L from 'leaflet';
import { DataKey, FormattedData } from '@shared/models/widget.models'; import { DataKey, FormattedData } from '@shared/models/widget.models';
import { ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer'; import { isSameShapeStyle, ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer';
import { TbMap } from '@home/components/widget/lib/maps/map'; import { TbMap } from '@home/components/widget/lib/maps/map';
import { Observable } from 'rxjs'; import { Observable, Subscription } from 'rxjs';
import { isNotEmptyStr, isString } from '@core/utils'; import { isNotEmptyStr, isString } from '@core/utils';
import { import {
TbLatestDataLayerItem, TbLatestDataLayerItem,
@ -23,7 +24,10 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
private polygonContainer: L.FeatureGroup; private polygonContainer: L.FeatureGroup;
private polygon: L.Polygon; private polygon: L.Polygon;
private polygonStyleInfo: ShapeStyleInfo; private polygonStyleInfo: ShapeStyleInfo;
private styleSubscription: Subscription;
private appliedGeometryKey: string;
private editing = false; private editing = false;
private pendingGeometryUpdate = false;
constructor(data: FormattedData<TbMapDatasource>, constructor(data: FormattedData<TbMapDatasource>,
dsData: FormattedData<TbMapDatasource>[], dsData: FormattedData<TbMapDatasource>[],
@ -41,6 +45,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
} }
public remove() { public remove() {
this.styleSubscription?.unsubscribe();
super.remove(); super.remove();
if (this.polygonStyleInfo?.patternId) { if (this.polygonStyleInfo?.patternId) {
this.dataLayer.getMap().unUseShapePattern(this.polygonStyleInfo.patternId); this.dataLayer.getMap().unUseShapePattern(this.polygonStyleInfo.patternId);
@ -49,6 +54,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
protected create(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): L.Layer { protected create(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): L.Layer {
const polyData = this.dataLayer.extractPolygonCoordinates(data); const polyData = this.dataLayer.extractPolygonCoordinates(data);
this.appliedGeometryKey = this.geometryKey(data);
const polyConstructor = isCutPolygon(polyData) || polyData.length !== 2 ? L.polygon : L.rectangle; const polyConstructor = isCutPolygon(polyData) || polyData.length !== 2 ? L.polygon : L.rectangle;
this.polygon = polyConstructor(polyData as (TbPolygonRawCoordinates & L.LatLngTuple[]), { this.polygon = polyConstructor(polyData as (TbPolygonRawCoordinates & L.LatLngTuple[]), {
noClip: true, noClip: true,
@ -56,7 +62,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
bubblingMouseEvents: !this.dataLayer.isEditMode() bubblingMouseEvents: !this.dataLayer.isEditMode()
}); });
this.dataLayer.getShapeStyle(data, dsData, this.polygonStyleInfo?.patternId).subscribe((styleInfo) => { this.styleSubscription = this.dataLayer.getShapeStyle(data, dsData, this.polygonStyleInfo?.patternId).subscribe((styleInfo) => {
this.polygonStyleInfo = styleInfo; this.polygonStyleInfo = styleInfo;
if (this.polygon) { if (this.polygon) {
this.polygon.setStyle(this.polygonStyleInfo.style); this.polygon.setStyle(this.polygonStyleInfo.style);
@ -80,19 +86,21 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
} }
protected doUpdate(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void { protected doUpdate(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void {
this.dataLayer.getShapeStyle(data, dsData, this.polygonStyleInfo?.patternId).subscribe((styleInfo) => { this.styleSubscription?.unsubscribe();
this.styleSubscription = this.dataLayer.getShapeStyle(data, dsData, this.polygonStyleInfo?.patternId).subscribe((styleInfo) => {
const styleChanged = !isSameShapeStyle(this.polygonStyleInfo, styleInfo);
this.polygonStyleInfo = styleInfo; this.polygonStyleInfo = styleInfo;
this.updatePolygonShape(data); const geometryChanged = this.updatePolygonShape(data);
this.updateTooltip(data, dsData); this.updateTooltip(data, dsData);
this.updateLabel(data, dsData); this.updateLabel(data, dsData, geometryChanged);
if (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled()) { if (styleChanged && (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled())) {
this.polygon.setStyle(this.polygonStyleInfo.style); this.polygon.setStyle(this.polygonStyleInfo.style);
} }
}); });
} }
protected doInvalidateCoordinates(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void { protected doInvalidateCoordinates(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void {
this.updatePolygonShape(data); this.updatePolygonShape(data, true);
this.updateLabel(data, dsData); this.updateLabel(data, dsData);
} }
@ -130,6 +138,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
protected disableDrag(): void { protected disableDrag(): void {
this.polygon.pm.disableLayerDrag(); this.polygon.pm.disableLayerDrag();
this.polygon.off('pm:dragstart'); this.polygon.off('pm:dragstart');
this.polygon.off('pm:drag');
this.polygon.off('pm:dragend'); this.polygon.off('pm:dragend');
} }
@ -292,6 +301,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
const map = this.dataLayer.getMap().getMap(); const map = this.dataLayer.getMap().getMap();
map.pm.disableGlobalCutMode(); map.pm.disableGlobalCutMode();
cutButton?.setActive(false); cutButton?.setActive(false);
this.applyPendingGeometryUpdate();
} }
private enablePolygonRotateMode(rotateButton?: L.TB.ToolbarButton) { private enablePolygonRotateMode(rotateButton?: L.TB.ToolbarButton) {
@ -314,6 +324,14 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
this.polygon.off('pm:rotateend'); this.polygon.off('pm:rotateend');
this.polygon.off('pm:rotatedisable'); this.polygon.off('pm:rotatedisable');
rotateButton?.setActive(false); rotateButton?.setActive(false);
this.applyPendingGeometryUpdate();
}
private applyPendingGeometryUpdate() {
if (this.pendingGeometryUpdate) {
this.pendingGeometryUpdate = false;
this.reapplyData();
}
} }
private savePolygonCoordinates() { private savePolygonCoordinates() {
@ -329,12 +347,27 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
} }
} }
this.dataLayer.savePolygonCoordinates(this.data, coordinates).subscribe(); this.dataLayer.savePolygonCoordinates(this.data, coordinates).subscribe();
this.pendingGeometryUpdate = false;
this.appliedGeometryKey = null;
this.markDataStale();
}
private geometryKey(data: FormattedData<TbMapDatasource>): string {
const rawPolyData = data[this.settings.polygonKey.label];
return isString(rawPolyData) ? rawPolyData : JSON.stringify(rawPolyData);
} }
private updatePolygonShape(data: FormattedData<TbMapDatasource>) { private updatePolygonShape(data: FormattedData<TbMapDatasource>, force = false): boolean {
if (this.editing) { if (this.editing) {
return; this.pendingGeometryUpdate = true;
this.markDataStale();
return false;
}
const geometryKey = this.geometryKey(data);
if (!force && geometryKey === this.appliedGeometryKey) {
return false;
} }
this.appliedGeometryKey = geometryKey;
const polyData = this.dataLayer.extractPolygonCoordinates(data) as TbPolyData; const polyData = this.dataLayer.extractPolygonCoordinates(data) as TbPolyData;
if (isCutPolygon(polyData) || polyData.length !== 2) { if (isCutPolygon(polyData) || polyData.length !== 2) {
if (this.polygon instanceof L.Rectangle) { if (this.polygon instanceof L.Rectangle) {
@ -354,6 +387,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
const bounds = new L.LatLngBounds(polyData as L.LatLngTuple[]); const bounds = new L.LatLngBounds(polyData as L.LatLngTuple[]);
(this.polygon as L.Rectangle).setBounds(bounds); (this.polygon as L.Rectangle).setBounds(bounds);
} }
return true;
} }
} }

59
ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/polylines-data-layer.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { import {
defaultBasePolylinesDataLayerSettings, defaultBasePolylinesDataLayerSettings,
isCutPolygon, isCutPolygon,
@ -13,9 +14,9 @@ import {
} from '@shared/models/widget/maps/map.models'; } from '@shared/models/widget/maps/map.models';
import L from 'leaflet'; import L from 'leaflet';
import { DataKey, FormattedData } from '@shared/models/widget.models'; import { DataKey, FormattedData } from '@shared/models/widget.models';
import { ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer'; import { isSameShapeStyle, ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer';
import { TbMap } from '@home/components/widget/lib/maps/map'; import { TbMap } from '@home/components/widget/lib/maps/map';
import { Observable } from 'rxjs'; import { Observable, Subscription } from 'rxjs';
import { isNotEmptyStr, isString } from '@core/utils'; import { isNotEmptyStr, isString } from '@core/utils';
import { import {
TbLatestDataLayerItem, TbLatestDataLayerItem,
@ -28,7 +29,10 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
private polylineContainer: L.FeatureGroup; private polylineContainer: L.FeatureGroup;
private polyline: L.Polyline; private polyline: L.Polyline;
private polylineStyleInfo: ShapeStyleInfo; private polylineStyleInfo: ShapeStyleInfo;
private styleSubscription: Subscription;
private appliedGeometryKey: string;
private editing = false; private editing = false;
private pendingGeometryUpdate = false;
constructor(data: FormattedData<TbMapDatasource>, constructor(data: FormattedData<TbMapDatasource>,
dsData: FormattedData<TbMapDatasource>[], dsData: FormattedData<TbMapDatasource>[],
@ -46,6 +50,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
} }
public remove() { public remove() {
this.styleSubscription?.unsubscribe();
super.remove(); super.remove();
if (this.polylineStyleInfo?.patternId) { if (this.polylineStyleInfo?.patternId) {
this.dataLayer.getMap().unUseShapePattern(this.polylineStyleInfo.patternId); this.dataLayer.getMap().unUseShapePattern(this.polylineStyleInfo.patternId);
@ -54,6 +59,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
protected create(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): L.Layer { protected create(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): L.Layer {
const polyData = this.dataLayer.extractPolylineCoordinates(data); const polyData = this.dataLayer.extractPolylineCoordinates(data);
this.appliedGeometryKey = this.geometryKey(data);
const polyConstructor = L.polyline; const polyConstructor = L.polyline;
this.polyline = polyConstructor(polyData as (TbPolylineRawCoordinates & L.LatLngTuple[]), { this.polyline = polyConstructor(polyData as (TbPolylineRawCoordinates & L.LatLngTuple[]), {
noClip: true, noClip: true,
@ -61,7 +67,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
bubblingMouseEvents: !this.dataLayer.isEditMode() bubblingMouseEvents: !this.dataLayer.isEditMode()
}); });
this.dataLayer.getStrokeStyle(data, dsData, this.polylineStyleInfo?.patternId).subscribe((styleInfo) => { this.styleSubscription = this.dataLayer.getStrokeStyle(data, dsData, this.polylineStyleInfo?.patternId).subscribe((styleInfo) => {
this.polylineStyleInfo = styleInfo; this.polylineStyleInfo = styleInfo;
if (this.polyline) { if (this.polyline) {
this.polyline.setStyle(this.polylineStyleInfo.style); this.polyline.setStyle(this.polylineStyleInfo.style);
@ -85,20 +91,23 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
} }
protected doUpdate(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void { protected doUpdate(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void {
this.dataLayer.getStrokeStyle(data, dsData, this.polylineStyleInfo?.patternId).subscribe((styleInfo) => { this.styleSubscription?.unsubscribe();
this.styleSubscription = this.dataLayer.getStrokeStyle(data, dsData, this.polylineStyleInfo?.patternId).subscribe((styleInfo) => {
const styleChanged = !isSameShapeStyle(this.polylineStyleInfo, styleInfo);
this.polylineStyleInfo = styleInfo; this.polylineStyleInfo = styleInfo;
this.updatePolylineShape(data); const geometryChanged = this.updatePolylineShape(data);
this.updateTooltip(data, dsData); this.updateTooltip(data, dsData);
this.updateLabel(data, dsData); this.updateLabel(data, dsData, geometryChanged);
if (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled()) { if (styleChanged && (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled())) {
this.polyline.setStyle(this.polylineStyleInfo.style); this.polyline.setStyle(this.polylineStyleInfo.style);
} }
}); });
} }
protected doInvalidateCoordinates(data: FormattedData<TbMapDatasource>, _dsData: FormattedData<TbMapDatasource>[]): void { protected doInvalidateCoordinates(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void {
this.updatePolylineShape(data); this.updatePolylineShape(data, true);
this.updateLabel(data, dsData);
} }
protected addItemClass(clazz: string): void { protected addItemClass(clazz: string): void {
@ -135,6 +144,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
protected disableDrag(): void { protected disableDrag(): void {
this.polyline.pm.disableLayerDrag(); this.polyline.pm.disableLayerDrag();
this.polyline.off('pm:dragstart'); this.polyline.off('pm:dragstart');
this.polyline.off('pm:drag');
this.polyline.off('pm:dragend'); this.polyline.off('pm:dragend');
} }
@ -312,6 +322,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
const map = this.dataLayer.getMap().getMap(); const map = this.dataLayer.getMap().getMap();
map.pm.disableGlobalCutMode(); map.pm.disableGlobalCutMode();
cutButton?.setActive(false); cutButton?.setActive(false);
this.applyPendingGeometryUpdate();
} }
private enablePolylineRotateMode(rotateButton?: L.TB.ToolbarButton) { private enablePolylineRotateMode(rotateButton?: L.TB.ToolbarButton) {
@ -334,6 +345,14 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
this.polyline.off('pm:rotateend'); this.polyline.off('pm:rotateend');
this.polyline.off('pm:rotatedisable'); this.polyline.off('pm:rotatedisable');
rotateButton?.setActive(false); rotateButton?.setActive(false);
this.applyPendingGeometryUpdate();
}
private applyPendingGeometryUpdate() {
if (this.pendingGeometryUpdate) {
this.pendingGeometryUpdate = false;
this.reapplyData();
}
} }
private savePolylineCoordinates() { private savePolylineCoordinates() {
@ -349,12 +368,27 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
} }
} }
this.dataLayer.savePolylineCoordinates(this.data, coordinates).subscribe(); this.dataLayer.savePolylineCoordinates(this.data, coordinates).subscribe();
this.pendingGeometryUpdate = false;
this.appliedGeometryKey = null;
this.markDataStale();
}
private geometryKey(data: FormattedData<TbMapDatasource>): string {
const rawPolyData = data[this.settings.polylineKey.label];
return isString(rawPolyData) ? rawPolyData : JSON.stringify(rawPolyData);
} }
private updatePolylineShape(data: FormattedData<TbMapDatasource>) { private updatePolylineShape(data: FormattedData<TbMapDatasource>, force = false): boolean {
if (this.editing) { if (this.editing) {
return; this.pendingGeometryUpdate = true;
this.markDataStale();
return false;
} }
const geometryKey = this.geometryKey(data);
if (!force && geometryKey === this.appliedGeometryKey) {
return false;
}
this.appliedGeometryKey = geometryKey;
const polyData = this.dataLayer.extractPolylineCoordinates(data) as TbPolylineData; const polyData = this.dataLayer.extractPolylineCoordinates(data) as TbPolylineData;
if (this.polyline instanceof L.Polyline && !(this.polyline instanceof L.Rectangle)) { if (this.polyline instanceof L.Polyline && !(this.polyline instanceof L.Rectangle)) {
@ -376,6 +410,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
this.polyline.addTo(this.polylineContainer); this.polyline.addTo(this.polylineContainer);
this.editModeUpdated(); this.editModeUpdated();
} }
return true;
} }
} }

18
ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/shapes-data-layer.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { import {
DataLayerColorSettings, DataLayerColorSettings,
loadImageWithAspect, loadImageWithAspect,
@ -61,6 +62,21 @@ export interface ShapeStyleInfo {
style: L.PathOptions; style: L.PathOptions;
} }
export const isSameShapeStyle = (a: ShapeStyleInfo, b: ShapeStyleInfo): boolean => {
if (!a || !b) {
return false;
}
if (a === b) {
return true;
}
if (a.patternId !== b.patternId) {
return false;
}
const aKeys = Object.keys(a.style);
const bKeys = Object.keys(b.style);
return aKeys.length === bKeys.length && aKeys.every(key => a.style[key] === b.style[key]);
};
abstract class ShapePatternProcessor<S = any> { abstract class ShapePatternProcessor<S = any> {
static fromSettings(dataLayer: TbMapDataLayer, static fromSettings(dataLayer: TbMapDataLayer,

154
ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/trips-data-layer.ts

@ -7,15 +7,16 @@ import {
defaultBaseTripsDataLayerSettings, defaultBaseTripsDataLayerSettings,
findRotationAngle, findRotationAngle,
interpolateLineSegment, interpolateLineSegment,
MapDataLayerType, MarkerType, MapBooleanFunction,
MapDataLayerType, MarkerIconInfo, MarkerType,
TbMapDatasource, TbMapDatasource,
TripsDataLayerSettings TripsDataLayerSettings
} from '@shared/models/widget/maps/map.models'; } from '@shared/models/widget/maps/map.models';
import { forkJoin, Observable } from 'rxjs'; import { forkJoin, Observable, Subscription } from 'rxjs';
import { DataKey, FormattedData, WidgetActionType } from '@shared/models/widget.models'; import { DataKey, FormattedData, WidgetActionType } from '@shared/models/widget.models';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import L from 'leaflet'; import L from 'leaflet';
import { deepClone, isDefined, isUndefined, plainColorFromVariable } from '@core/utils'; import { deepClone, isDefined, isEqual, isUndefined, plainColorFromVariable } from '@core/utils';
import { TbMap } from '@home/components/widget/lib/maps/map'; import { TbMap } from '@home/components/widget/lib/maps/map';
import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; import { DataKeyType } from '@shared/models/telemetry/telemetry.models';
import moment from 'moment/moment'; import moment from 'moment/moment';
@ -27,7 +28,13 @@ import {
TbDataLayerItem, TbDataLayerItem,
TbMapDataLayer TbMapDataLayer
} from '@home/components/widget/lib/maps/data-layer/map-data-layer'; } from '@home/components/widget/lib/maps/data-layer/map-data-layer';
import { MarkerDataProcessor } from '@home/components/widget/lib/maps/data-layer/markers-data-layer'; import {
createPlaceholderMarkerIcon,
isRotationOnlyIconChange,
isSameMarkerIcon,
MarkerDataProcessor
} from '@home/components/widget/lib/maps/data-layer/markers-data-layer';
import { CompiledTbFunction } from '@shared/models/js-function.models';
type TripRouteData = {[time: number]: FormattedData<TbMapDatasource>}; type TripRouteData = {[time: number]: FormattedData<TbMapDatasource>};
@ -39,13 +46,19 @@ export interface PointItem {
class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsDataLayer, L.FeatureGroup> { class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsDataLayer, L.FeatureGroup> {
private tripRouteData: TripRouteData; private tripRouteData: TripRouteData;
private timePoints: number[];
private marker: L.Marker; private marker: L.Marker;
private markerTooltip: L.Popup; private markerTooltip: L.Popup;
private markerIconSubscription: Subscription;
private appliedIconInfo: MarkerIconInfo;
private labelOffset: L.PointTuple; private labelOffset: L.PointTuple;
private labelContent: string;
private boundLabelOffset: L.PointTuple;
private polyline: L.Polyline; private polyline: L.Polyline;
private polylineDecorator: L.PolylineDecorator; private polylineDecorator: L.PolylineDecorator;
private appliedPathColor: string;
private pointsContainer: L.FeatureGroup; private pointsContainer: L.FeatureGroup;
private points = new Map<string, PointItem>(); private points = new Map<string, PointItem>();
@ -102,7 +115,7 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
if (this.latestData) { if (this.latestData) {
this.pointData = {...this.pointData, ...this.latestData}; this.pointData = {...this.pointData, ...this.latestData};
} }
this.updatePath(); this.updatePathAppearance();
this.updateMarker(); this.updateMarker();
} }
@ -114,6 +127,7 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
} }
public remove() { public remove() {
this.markerIconSubscription?.unsubscribe();
if (this.marker) { if (this.marker) {
this.layer.removeLayer(this.marker); this.layer.removeLayer(this.marker);
this.marker.off(); this.marker.off();
@ -125,11 +139,9 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
this.layer.off(); this.layer.off();
} }
public calculateAnchors(): number[] { public calculateAnchors(snapFilter: CompiledTbFunction<MapBooleanFunction>,
const entries = Object.entries(this.tripRouteData); dsData: FormattedData<TbMapDatasource>[]): number[] {
const dsData = this.dataLayer.getMap().getData(); return this.timePoints.filter(time => snapFilter.execute(this.tripRouteData[time], dsData));
return entries.filter(data => this.dataLayer.getMap().getLocationSnapFilterFunction().execute(data[1], dsData))
.map(data => parseInt(data[0], 10));
} }
private create() { private create() {
@ -157,6 +169,7 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
return; return;
} }
this.marker = L.marker(location, { this.marker = L.marker(location, {
icon: createPlaceholderMarkerIcon(),
tbMarkerData: this.pointData, tbMarkerData: this.pointData,
snapIgnore: true snapIgnore: true
}); });
@ -218,6 +231,7 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
this.polylineDecorator = new L.PolylineDecorator(this.polyline, this.dataLayer.getPathDecoratorStyle(pathStyle.color)); this.polylineDecorator = new L.PolylineDecorator(this.polyline, this.dataLayer.getPathDecoratorStyle(pathStyle.color));
this.polylineDecorator.addTo(this.layer); this.polylineDecorator.addTo(this.layer);
} }
this.appliedPathColor = pathStyle.color;
} }
} }
@ -302,24 +316,37 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
if (this.settings.showPath) { if (this.settings.showPath) {
const dsData = this.dataLayer.getMap().getData(); const dsData = this.dataLayer.getMap().getData();
const pathStyle = this.dataLayer.getPathStyle(this.pointData, dsData); const pathStyle = this.dataLayer.getPathStyle(this.pointData, dsData);
this.polyline.setStyle(pathStyle); if (pathStyle.color !== this.appliedPathColor) {
if (this.settings.usePathDecorator) { this.polyline.setStyle(pathStyle);
this.polylineDecorator.setPatterns(this.dataLayer.getPathDecoratorStyle(pathStyle.color).patterns) if (this.settings.usePathDecorator) {
this.polylineDecorator.setPatterns(this.dataLayer.getPathDecoratorStyle(pathStyle.color).patterns)
}
this.appliedPathColor = pathStyle.color;
} }
} }
} }
private updateMarkerIcon(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) { private updateMarkerIcon(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) {
if (this.settings.showMarker && this.marker) { if (this.settings.showMarker && this.marker) {
this.dataLayer.dataProcessor.createMarkerIcon(data, dsData, data.rotationAngle).subscribe( this.markerIconSubscription?.unsubscribe();
this.markerIconSubscription = this.dataLayer.dataProcessor.createMarkerIcon(data, dsData, data.rotationAngle).subscribe(
(iconInfo) => { (iconInfo) => {
const options = deepClone(iconInfo.icon.options); if (!isSameMarkerIcon(this.appliedIconInfo, iconInfo)) {
this.marker.setIcon(iconInfo.icon); const rotatedElement = this.marker.getElement()?.firstElementChild as HTMLElement;
const anchor = options.iconAnchor; if (rotatedElement && isRotationOnlyIconChange(this.appliedIconInfo, iconInfo)) {
if (anchor && Array.isArray(anchor)) { rotatedElement.style.transform = `rotate(${data.rotationAngle}deg)`;
this.labelOffset = [iconInfo.size[0] / 2 - anchor[0], 10 - anchor[1]]; this.marker.options.icon = iconInfo.icon;
} else { } else {
this.labelOffset = [0, -iconInfo.size[1] * this.dataLayer.markerOffset[1] + 10]; const options = deepClone(iconInfo.icon.options);
this.marker.setIcon(iconInfo.icon);
const anchor = options.iconAnchor;
if (anchor && Array.isArray(anchor)) {
this.labelOffset = [iconInfo.size[0] / 2 - anchor[0], 10 - anchor[1]];
} else {
this.labelOffset = [0, -iconInfo.size[1] * this.dataLayer.markerOffset[1] + 10];
}
}
this.appliedIconInfo = iconInfo;
} }
this.updateMarkerLabel(data, dsData); this.updateMarkerLabel(data, dsData);
} }
@ -329,11 +356,20 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
private updateMarkerLabel(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) { private updateMarkerLabel(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) {
if (this.settings.label.show) { if (this.settings.label.show) {
this.marker.unbindTooltip();
const label = this.dataLayer.dataLayerLabelProcessor.processPattern(data, dsData); const label = this.dataLayer.dataLayerLabelProcessor.processPattern(data, dsData);
const labelColor = this.dataLayer.getCtx().widgetConfig.color; const labelColor = this.dataLayer.getCtx().widgetConfig.color;
const content: L.Content = `<div style="color: ${labelColor};"><b>${label}</b></div>`; const content = `<div style="color: ${labelColor};"><b>${label}</b></div>`;
this.marker.bindTooltip(content, { className: 'tb-marker-label', permanent: true, direction: 'top', offset: this.labelOffset }); const offsetChanged = !isEqual(this.boundLabelOffset, this.labelOffset);
if (this.marker.getTooltip() && !offsetChanged) {
if (content !== this.labelContent) {
this.marker.setTooltipContent(content);
}
} else {
this.marker.unbindTooltip();
this.marker.bindTooltip(content, { className: 'tb-marker-label', permanent: true, direction: 'top', offset: this.labelOffset });
}
this.labelContent = content;
this.boundLabelOffset = this.labelOffset;
} }
} }
@ -386,6 +422,7 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
const endPoint = this.dataLayer.dataProcessor.extractLocation(result[timeStamp[timeStamp.length - 1]], dsData); const endPoint = this.dataLayer.dataProcessor.extractLocation(result[timeStamp[timeStamp.length - 1]], dsData);
result[timeStamp[timeStamp.length - 1]].rotationAngle += findRotationAngle(startPoint, endPoint); result[timeStamp[timeStamp.length - 1]].rotationAngle += findRotationAngle(startPoint, endPoint);
} }
this.timePoints = timeStamp.map(Number).sort((a, b) => a - b);
return result; return result;
} }
@ -394,19 +431,17 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
this.currentTime = this.dataLayer.getMap().getCurrentTime(); this.currentTime = this.dataLayer.getMap().getCurrentTime();
let currentPosition = this.tripRouteData[this.currentTime]; let currentPosition = this.tripRouteData[this.currentTime];
if (!currentPosition) { if (!currentPosition) {
const timePoints = Object.keys(this.tripRouteData).map(item => parseInt(item, 10)); const timePoints = this.timePoints;
for (let i = 1; i < timePoints.length; i++) { const i = this.findLastTimePointBefore(this.currentTime);
if (timePoints[i - 1] < this.currentTime && timePoints[i] > this.currentTime) { if (i >= 0 && i + 1 < timePoints.length && timePoints[i + 1] > this.currentTime) {
const beforePosition = this.tripRouteData[timePoints[i - 1]]; const beforePosition = this.tripRouteData[timePoints[i]];
const afterPosition = this.tripRouteData[timePoints[i]]; const afterPosition = this.tripRouteData[timePoints[i + 1]];
const ratio = calculateInterpolationRatio(timePoints[i - 1], timePoints[i], this.currentTime); const ratio = calculateInterpolationRatio(timePoints[i], timePoints[i + 1], this.currentTime);
currentPosition = { currentPosition = {
...beforePosition, ...beforePosition,
time: this.currentTime, time: this.currentTime,
...interpolateLineSegment(beforePosition, afterPosition, this.settings.xKey.label, this.settings.yKey.label, ratio) ...interpolateLineSegment(beforePosition, afterPosition, this.settings.xKey.label, this.settings.yKey.label, ratio)
}; };
break;
}
} }
} }
if (!currentPosition) { if (!currentPosition) {
@ -416,6 +451,22 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
} }
} }
private findLastTimePointBefore(time: number): number {
let low = 0;
let high = this.timePoints.length - 1;
let result = -1;
while (low <= high) {
const mid = (low + high) >> 1;
if (this.timePoints[mid] < time) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
} }
export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbTripDataItem> { export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbTripDataItem> {
@ -430,7 +481,7 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
public pointTooltipProcessor: DataLayerPatternProcessor; public pointTooltipProcessor: DataLayerPatternProcessor;
private rawTripsData: FormattedData<TbMapDatasource>[][]; private rawTripsData: FormattedData<TbMapDatasource>[][];
private latestTripsData: FormattedData<TbMapDatasource>[]; private latestTripsDataByEntity = new Map<string, FormattedData<TbMapDatasource>>();
constructor(protected map: TbMap<any>, constructor(protected map: TbMap<any>,
inputSettings: TripsDataLayerSettings) { inputSettings: TripsDataLayerSettings) {
@ -451,7 +502,7 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
this.rawTripsData = this.rawTripsData =
tripsData.filter(d => !!d.length && d[0].$datasource.mapDataIds.includes(this.mapDataId)).map( tripsData.filter(d => !!d.length && d[0].$datasource.mapDataIds.includes(this.mapDataId)).map(
item => this.clearIncorrectFirsLastDatapoint(item)).filter(arr => arr.length); item => this.clearIncorrectFirsLastDatapoint(item)).filter(arr => arr.length);
this.latestTripsData = tripsLatestData.filter(d => d.$datasource.mapDataIds.includes(this.mapDataId)); this.setLatestTripsData(tripsLatestData);
this.rawTripsData.forEach((dataSource) => { this.rawTripsData.forEach((dataSource) => {
minTime = Math.min(dataSource[0].time, minTime); minTime = Math.min(dataSource[0].time, minTime);
maxTime = Math.max(dataSource[dataSource.length - 1].time, maxTime); maxTime = Math.max(dataSource[dataSource.length - 1].time, maxTime);
@ -467,7 +518,7 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
if (tripItem) { if (tripItem) {
tripItem.update(rawTripData); tripItem.update(rawTripData);
} else { } else {
const latestData = this.latestTripsData.find(d => d.entityId === entityId); const latestData = this.latestTripsDataByEntity.get(entityId);
tripItem = new TbTripDataItem(rawTripData, latestData, this.settings, this); tripItem = new TbTripDataItem(rawTripData, latestData, this.settings, this);
this.layerItems.set(entityId, tripItem); this.layerItems.set(entityId, tripItem);
} }
@ -479,10 +530,9 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
} }
public updateTripsLatestData(tripsLatestData: FormattedData<TbMapDatasource>[]) { public updateTripsLatestData(tripsLatestData: FormattedData<TbMapDatasource>[]) {
this.latestTripsData = tripsLatestData.filter(d => d.$datasource.mapDataIds.includes(this.mapDataId)); this.setLatestTripsData(tripsLatestData);
this.layerItems.forEach((item, entityId) => { this.layerItems.forEach((item, entityId) => {
const latestData = this.latestTripsData.find(d => d.entityId === entityId); item.updateLatestData(this.latestTripsDataByEntity.get(entityId));
item.updateLatestData(latestData);
}); });
} }
@ -499,12 +549,13 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
} }
public calculateAnchors(): number[] { public calculateAnchors(): number[] {
let anchors: number[] = []; const anchors = new Set<number>();
const snapFilter = this.map.getLocationSnapFilterFunction();
const dsData = this.map.getData();
this.layerItems.forEach(item => { this.layerItems.forEach(item => {
const tripAnchors = item.calculateAnchors(); item.calculateAnchors(snapFilter, dsData).forEach(anchor => anchors.add(anchor));
anchors = [...new Set([...anchors, ...tripAnchors])];
}); });
return anchors; return [...anchors];
} }
public getPathStyle(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): L.PolylineOptions { public getPathStyle(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): L.PolylineOptions {
@ -616,6 +667,15 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
return forkJoin(setup$).pipe(map(() => null)); return forkJoin(setup$).pipe(map(() => null));
} }
private setLatestTripsData(tripsLatestData: FormattedData<TbMapDatasource>[]) {
this.latestTripsDataByEntity.clear();
for (const data of tripsLatestData) {
if (data.$datasource.mapDataIds.includes(this.mapDataId) && !this.latestTripsDataByEntity.has(data.entityId)) {
this.latestTripsDataByEntity.set(data.entityId, data);
}
}
}
private clearIncorrectFirsLastDatapoint(dataSource: FormattedData<TbMapDatasource>[]): FormattedData<TbMapDatasource>[] { private clearIncorrectFirsLastDatapoint(dataSource: FormattedData<TbMapDatasource>[]): FormattedData<TbMapDatasource>[] {
const firstValidIndex = dataSource.findIndex(this.hasValidLocation); const firstValidIndex = dataSource.findIndex(this.hasValidLocation);
if (firstValidIndex === -1) { if (firstValidIndex === -1) {

88
ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts

@ -5,7 +5,7 @@ import L, { TB } from 'leaflet';
import { guid, isDefinedAndNotNull, isNotEmptyStr } from '@core/utils'; import { guid, isDefinedAndNotNull, isNotEmptyStr } from '@core/utils';
import 'leaflet-providers'; import 'leaflet-providers';
import { GestureHandling } from 'leaflet-gesture-handling'; import { GestureHandling } from 'leaflet-gesture-handling';
import { Map as MapLibreGLMap, setWorkerUrl } from 'maplibre-gl'; import { LngLat, Map as MapLibreGLMap, setWorkerUrl } from 'maplibre-gl';
import '@geoman-io/leaflet-geoman-free'; import '@geoman-io/leaflet-geoman-free';
import 'leaflet.markercluster'; import 'leaflet.markercluster';
import { MatIconRegistry } from '@angular/material/icon'; import { MatIconRegistry } from '@angular/material/icon';
@ -1094,7 +1094,11 @@ const chinaProvider = (type: string, options?: L.TileLayerOptions): L.TB.TileLay
setWorkerUrl(new URL('assets/maplibre-gl/maplibre-gl-worker.mjs', document.baseURI).href); setWorkerUrl(new URL('assets/maplibre-gl/maplibre-gl-worker.mjs', document.baseURI).href);
// Same as MapLibre's own default maxZoom // Same as MapLibre's own default maxZoom
const MAP_LIBRE_GL_DEFAULT_MAX_ZOOM = 22; const mapLibreGlDefaultMaxZoom = 22;
// Web Mercator latitude limit
const mapLibreGlMaxLatitude = 85.051129;
// MapLibre renders the world plus 3 copies on each side; longitude limit in degrees
const mapLibreGlMaxLongitude = 180 + 3 * 360;
class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
@ -1107,11 +1111,13 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
private _offset: L.Point; private _offset: L.Point;
private _zooming: boolean; private _zooming: boolean;
private _glError = false; private _glError = false;
private _ownMaxBounds: L.LatLngBounds;
private _prevMaxBoundsViscosity: number;
constructor(options: TB.MapLibreGL.LeafletMapLibreGLMapOptions) { constructor(options: TB.MapLibreGL.LeafletMapLibreGLMapOptions) {
super(); super();
options = { options = {
maxZoom: MAP_LIBRE_GL_DEFAULT_MAX_ZOOM, maxZoom: mapLibreGlDefaultMaxZoom,
...options, ...options,
updateInterval: 32, updateInterval: 32,
padding: 0.1, padding: 0.1,
@ -1125,28 +1131,26 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
} }
beforeAdd(map: L.Map): this { beforeAdd(map: L.Map): this {
map._addZoomLimit(this); if (!this.options.overlay) {
map._addZoomLimit(this);
}
return this; return this;
} }
onAdd(map: L.Map): this { onAdd(map: L.Map): this {
let update = false;
if (!this._container) { if (!this._container) {
this._initContainer(); this._initContainer();
} else {
update = true;
} }
const paneName = this.getPaneName(); const paneName = this.getPaneName();
map.getPane(paneName).appendChild(this._container); map.getPane(paneName).appendChild(this._container);
this._initGL(); this._initGL();
this._limitPan(map);
this._offset = this._map.containerPointToLayerPoint([0, 0]); this._offset = this._map.containerPointToLayerPoint([0, 0]);
if ((this._map as any)._proxy && map.options.zoomAnimation) { if ((this._map as any)._proxy && map.options.zoomAnimation) {
L.DomEvent.on((map as any)._proxy, L.DomUtil.TRANSITION_END, this._transitionEnd, this); L.DomEvent.on((map as any)._proxy, L.DomUtil.TRANSITION_END, this._transitionEnd, this);
} }
if (update) { this._update();
this._update();
}
return this; return this;
} }
@ -1157,6 +1161,7 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
const paneName = this.getPaneName(); const paneName = this.getPaneName();
map.getPane(paneName).removeChild(this._container); map.getPane(paneName).removeChild(this._container);
map._removeZoomLimit(this); map._removeZoomLimit(this);
this._releasePan(map);
if (this._glMap) { if (this._glMap) {
this._glMap.remove(); this._glMap.remove();
@ -1221,13 +1226,16 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
} }
private _initGL() { private _initGL() {
const center = this._map.getCenter();
const options = L.extend({}, this.options, { const options = L.extend({}, this.options, {
container: this._container, container: this._container,
center: [center.lng, center.lat], center: this._getGLCenter(),
zoom: this._map.getZoom() - 1, zoom: this._map.getZoom() - 1,
attributionControl: false attributionControl: false,
transformConstrain: (lngLat: LngLat, zoom: number) => ({center: lngLat, zoom})
}); });
delete options.minZoom;
delete options.maxZoom;
delete options.overlay;
this._glError = false; this._glError = false;
try { try {
this._glMap = new MapLibreGLMap(options); this._glMap = new MapLibreGLMap(options);
@ -1276,30 +1284,68 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
offset = this._map.getSize().multiplyBy(this.options.padding), offset = this._map.getSize().multiplyBy(this.options.padding),
topLeft = this._map.containerPointToLayerPoint([0, 0]).subtract(offset); topLeft = this._map.containerPointToLayerPoint([0, 0]).subtract(offset);
L.DomUtil.setPosition(container, this._roundPoint(topLeft));
this._transformGL(gl);
if (container.clientWidth !== size.x || container.clientHeight !== size.y) { if (container.clientWidth !== size.x || container.clientHeight !== size.y) {
container.style.width = size.x + 'px'; container.style.width = size.x + 'px';
container.style.height = size.y + 'px'; container.style.height = size.y + 'px';
gl.resize(); gl.resize();
} }
this._transformGL(gl);
L.DomUtil.setPosition(container, this._roundPoint(topLeft.add([0, this._getGLCenterOffsetY()])));
} }
private _transformGL(gl: MapLibreGLMap) { private _transformGL(gl: MapLibreGLMap) {
const center = this._map.getCenter();
gl.jumpTo({ gl.jumpTo({
center: [center.lng, center.lat], center: this._getGLCenter(),
zoom: this._map.getZoom() - 1 zoom: this._map.getZoom() - 1
}); });
} }
private _getGLCenter(): LngLat {
const center = this._map.getCenter();
const lat = Math.max(-mapLibreGlMaxLatitude, Math.min(mapLibreGlMaxLatitude, center.lat));
return new LngLat(center.lng, lat);
}
private _getGLCenterOffsetY(): number {
const glCenter = this._getGLCenter();
const centerPoint = this._map.containerPointToLayerPoint(this._map.getSize().divideBy(2));
const glCenterPoint = this._map.latLngToLayerPoint([glCenter.lat, glCenter.lng]);
const offsetY = glCenterPoint.y - centerPoint.y;
return Number.isFinite(offsetY) ? offsetY : 0;
}
private _limitPan(map: L.Map) {
if (!this.options.overlay && !map.options.maxBounds) {
this._ownMaxBounds = L.latLngBounds([-mapLibreGlMaxLatitude, -mapLibreGlMaxLongitude],
[mapLibreGlMaxLatitude, mapLibreGlMaxLongitude]);
this._prevMaxBoundsViscosity = map.options.maxBoundsViscosity;
map.options.maxBoundsViscosity = 1;
map.setMaxBounds(this._ownMaxBounds);
}
}
private _releasePan(map: L.Map) {
if (this._ownMaxBounds && map.options.maxBounds === this._ownMaxBounds) {
map.setMaxBounds(null);
map.options.maxBoundsViscosity = this._prevMaxBoundsViscosity;
let handedOff = false;
map.eachLayer((layer) => {
if (!handedOff && layer !== this && layer instanceof MapLibreGLLayer && !layer.options.overlay) {
layer._limitPan(map);
handedOff = true;
}
});
}
this._ownMaxBounds = null;
}
private _pinchZoom() { private _pinchZoom() {
if (!this._glReady()) { return; } if (!this._glReady()) { return; }
this._glMap.jumpTo({ this._glMap.jumpTo({
zoom: this._map.getZoom() - 1, zoom: this._map.getZoom() - 1,
center: this._map.getCenter() center: this._getGLCenter()
}); });
} }
@ -1345,7 +1391,7 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
L.Util.requestAnimFrame(() => { L.Util.requestAnimFrame(() => {
if (!this._glReady()) { return; } if (!this._glReady()) { return; }
const zoom = this._map.getZoom(); const zoom = this._map.getZoom();
const center = this._map.getCenter(); const center = this._getGLCenter();
const offset = this._map.latLngToContainerPoint( const offset = this._map.latLngToContainerPoint(
this._map.getBounds().getNorthWest() this._map.getBounds().getNorthWest()
); );

3
ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts

@ -250,8 +250,7 @@ export abstract class TbMapLayer<S extends MapLayerSettings> {
} }
return L.TB.MapLibreGL.mapLibreGLLayer({ return L.TB.MapLibreGL.mapLibreGLLayer({
style: this.referenceLayerStyle(spec), style: this.referenceLayerStyle(spec),
// The reference layer is drawn over a raster base, so the base layer's zoom limit applies overlay: true
maxZoom: undefined
}); });
}) })
); );

17
ui-ngx/src/app/modules/home/components/widget/lib/maps/map.ts

@ -68,7 +68,7 @@ import { MapTimelinePanelComponent } from '@home/components/widget/lib/maps/pane
import { ComponentRef } from '@angular/core'; import { ComponentRef } from '@angular/core';
import { TbTripsDataLayer } from '@home/components/widget/lib/maps/data-layer/trips-data-layer'; import { TbTripsDataLayer } from '@home/components/widget/lib/maps/data-layer/trips-data-layer';
import { CompiledTbFunction } from '@shared/models/js-function.models'; import { CompiledTbFunction } from '@shared/models/js-function.models';
import { TbMapDataLayer } from '@home/components/widget/lib/maps/data-layer/map-data-layer'; import { TbMapDataLayer, tbFunctionUsesAdditionalData } from '@home/components/widget/lib/maps/data-layer/map-data-layer';
import { EntityType } from '@shared/models/entity-type.models'; import { EntityType } from '@shared/models/entity-type.models';
import { ShapePatternStorage } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer'; import { ShapePatternStorage } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer';
import { TbPolylineDataLayer } from '@home/components/widget/lib/maps/data-layer/polylines-data-layer'; import { TbPolylineDataLayer } from '@home/components/widget/lib/maps/data-layer/polylines-data-layer';
@ -122,6 +122,7 @@ export abstract class TbMap<S extends BaseMapSettings> {
protected timeLineComponentRef: ComponentRef<MapTimelinePanelComponent>; protected timeLineComponentRef: ComponentRef<MapTimelinePanelComponent>;
protected timeLineComponent: MapTimelinePanelComponent; protected timeLineComponent: MapTimelinePanelComponent;
protected locationSnapFilterFunction: CompiledTbFunction<MapBooleanFunction>; protected locationSnapFilterFunction: CompiledTbFunction<MapBooleanFunction>;
private locationSnapFilterUsesAdditionalData = false;
protected addMarkerDataLayers: TbLatestMapDataLayer<any>[]; protected addMarkerDataLayers: TbLatestMapDataLayer<any>[];
protected addPolygonDataLayers: TbLatestMapDataLayer<any>[]; protected addPolygonDataLayers: TbLatestMapDataLayer<any>[];
@ -223,6 +224,7 @@ export abstract class TbMap<S extends BaseMapSettings> {
} }
const setup = [this.doSetupControls()]; const setup = [this.doSetupControls()];
if (this.timeline && this.settings.tripTimeline.snapToRealLocation) { if (this.timeline && this.settings.tripTimeline.snapToRealLocation) {
this.locationSnapFilterUsesAdditionalData = tbFunctionUsesAdditionalData(this.settings.tripTimeline.locationSnapFilter);
setup.push(parseTbFunction<MapBooleanFunction>(this.getCtx().http, this.settings.tripTimeline.locationSnapFilter, ['data', 'dsData']).pipe( setup.push(parseTbFunction<MapBooleanFunction>(this.getCtx().http, this.settings.tripTimeline.locationSnapFilter, ['data', 'dsData']).pipe(
map((parsed) => { map((parsed) => {
this.locationSnapFilterFunction = parsed; this.locationSnapFilterFunction = parsed;
@ -964,7 +966,9 @@ export abstract class TbMap<S extends BaseMapSettings> {
undefined, undefined, el => el.datasource.entityId + el.datasource.mapDataIds[0]); undefined, undefined, el => el.datasource.entityId + el.datasource.mapDataIds[0]);
this.latestDataLayers.forEach(dl => dl.updateData(this.dsData)); this.latestDataLayers.forEach(dl => dl.updateData(this.dsData));
this.updateTripsAppearance(); this.updateTripsAppearance();
this.updateTripsAnchors(); if (this.locationSnapFilterUsesAdditionalData) {
this.updateTripsAnchors();
}
this.updateBounds(); this.updateBounds();
this.updateEditButtonsStates(); this.updateEditButtonsStates();
this.ctx.updateLabelPatterns(); this.ctx.updateLabelPatterns();
@ -1010,7 +1014,7 @@ export abstract class TbMap<S extends BaseMapSettings> {
} }
private updateTripsAppearance() { private updateTripsAppearance() {
this.tripDataLayers.forEach(dl => dl.updateAppearance()); this.tripDataLayers.filter(dl => !dl.canSkipUnchangedItems()).forEach(dl => dl.updateAppearance());
} }
private updateTripsTime() { private updateTripsTime() {
@ -1021,13 +1025,12 @@ export abstract class TbMap<S extends BaseMapSettings> {
if (this.timeline) { if (this.timeline) {
if (this.settings.tripTimeline.snapToRealLocation) { if (this.settings.tripTimeline.snapToRealLocation) {
// Recalculate anchors only for enabled layers // Recalculate anchors only for enabled layers
let anchors: number[] = []; const anchorSet = new Set<number>();
const enableTrips = this.tripDataLayers.filter(dl => dl.isEnabled()); const enableTrips = this.tripDataLayers.filter(dl => dl.isEnabled());
for (const tripsDataLayer of enableTrips) { for (const tripsDataLayer of enableTrips) {
const tripsAnchors = tripsDataLayer.calculateAnchors(); tripsDataLayer.calculateAnchors().forEach(anchor => anchorSet.add(anchor));
anchors = [...new Set([...anchors, ...tripsAnchors])];
} }
anchors.sort((a, b) => a - b); const anchors = [...anchorSet].sort((a, b) => a - b);
this.timeLineComponent.anchors = anchors; this.timeLineComponent.anchors = anchors;
} }
} }

83
ui-ngx/src/app/shared/models/widget/maps/map.models.ts

@ -26,7 +26,7 @@ import { materialColors } from '@shared/models/material.models';
import type L from 'leaflet'; import type L from 'leaflet';
import { TbFunction } from '@shared/models/js-function.models'; import { TbFunction } from '@shared/models/js-function.models';
import { Observable, Observer, of, switchMap } from 'rxjs'; import { Observable, Observer, of, switchMap } from 'rxjs';
import { map } from 'rxjs/operators'; import { finalize, map, shareReplay } from 'rxjs/operators';
import { ImagePipe } from '@shared/pipe/image.pipe'; import { ImagePipe } from '@shared/pipe/image.pipe';
import { MarkerIconContainer, MarkerShape } from '@shared/models/widget/maps/marker-shape.models'; import { MarkerIconContainer, MarkerShape } from '@shared/models/widget/maps/marker-shape.models';
import { ColorRange, DateFormatSettings, simpleDateFormat } from '@shared/models/widget-settings.models'; import { ColorRange, DateFormatSettings, simpleDateFormat } from '@shared/models/widget-settings.models';
@ -1561,28 +1561,40 @@ const mergeMapDatasource = (target: TbMapDatasource, source: TbMapDatasource): T
} }
const imageAspectMap: {[key: string]: ImageWithAspect} = {}; const imageAspectMap: {[key: string]: ImageWithAspect} = {};
const imageAspectLoading: {[key: string]: Observable<ImageWithAspect>} = {};
const imageLoader = (imageUrl: string): Observable<HTMLImageElement> => new Observable((observer: Observer<HTMLImageElement>) => { const measureAttachedImage = (image: HTMLImageElement): [number, number] => {
const image = document.createElement('img'); // support IE
image.style.position = 'absolute'; image.style.position = 'absolute';
image.style.left = '-99999px'; image.style.left = '-99999px';
image.style.top = '-99999px'; image.style.top = '-99999px';
image.onload = () => {
observer.next(image);
document.body.removeChild(image);
observer.complete();
};
image.onerror = err => {
observer.error(err);
document.body.removeChild(image);
observer.complete();
};
document.body.appendChild(image); document.body.appendChild(image);
image.src = imageUrl; const size: [number, number] = [image.width, image.height];
}); image.remove();
return size;
};
export const loadImageSize = (imageUrl: string): Observable<[number, number]> => export const loadImageSize = (imageUrl: string): Observable<[number, number]> =>
imageLoader(imageUrl).pipe(map(image => [image.width, image.height])); new Observable((observer: Observer<[number, number]>) => {
const image = new Image();
image.onload = () => {
if (image.naturalWidth > 0 && image.naturalHeight > 0) {
observer.next([image.naturalWidth, image.naturalHeight]);
} else {
observer.next(measureAttachedImage(image));
}
observer.complete();
};
image.onerror = err => {
observer.error(err);
};
image.src = imageUrl;
return () => {
image.remove();
if (!image.complete) {
image.removeAttribute('src');
}
};
});
export interface ImageWithAspect { export interface ImageWithAspect {
url: string; url: string;
@ -1592,32 +1604,37 @@ export interface ImageWithAspect {
} }
export const loadImageWithAspect = (imagePipe: ImagePipe, imageUrl: string): Observable<ImageWithAspect> => { export const loadImageWithAspect = (imagePipe: ImagePipe, imageUrl: string): Observable<ImageWithAspect> => {
if (imageUrl?.length) { if (!imageUrl?.length) {
const hash = hashCode(imageUrl); return of(null);
let imageWithAspect = imageAspectMap[hash]; }
if (imageWithAspect) { const hash = hashCode(imageUrl);
return of(imageWithAspect); const imageWithAspect = imageAspectMap[hash];
} else { if (imageWithAspect) {
return imagePipe.transform(imageUrl, {asString: true, ignoreLoadingImage: true}).pipe( return of(imageWithAspect);
} else {
let loading$ = imageAspectLoading[hash];
if (!loading$) {
loading$ = imagePipe.transform(imageUrl, {asString: true, ignoreLoadingImage: true}).pipe(
switchMap((res) => { switchMap((res) => {
const url = res as string; const url = res as string;
return loadImageSize(url).pipe( return loadImageSize(url).pipe(
map((size) => { map(([width, height]) => {
imageWithAspect = { const imageWithAspect: ImageWithAspect = {url, width, height, aspect: width / height};
url,
width: size[0],
height: size[1],
aspect: size[0]/size[1]
};
imageAspectMap[hash] = imageWithAspect; imageAspectMap[hash] = imageWithAspect;
return imageWithAspect; return imageWithAspect;
}) })
); );
}) }),
finalize(() => {
if (imageAspectLoading[hash] === loading$) {
delete imageAspectLoading[hash];
}
}),
shareReplay({bufferSize: 1, refCount: false})
); );
imageAspectLoading[hash] = loading$;
} }
} else { return loading$;
return of(null);
} }
}; };

1
ui-ngx/src/typings/leaflet-extend-tb.d.ts

@ -301,6 +301,7 @@ declare module 'leaflet' {
interface LeafletMapLibreGLMapOptions extends L.InteractiveLayerOptions, Omit<MapLibreGLMapOptions, "container"> { interface LeafletMapLibreGLMapOptions extends L.InteractiveLayerOptions, Omit<MapLibreGLMapOptions, "container"> {
updateInterval?: number; updateInterval?: number;
overlay?: boolean;
padding?: number; padding?: number;
className?: string; className?: string;
} }

Loading…
Cancel
Save