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-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
CirclesDataLayerSettings,
defaultBaseCirclesDataLayerSettings,
@ -9,9 +10,9 @@ import {
} from '@shared/models/widget/maps/map.models';
import L from 'leaflet';
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 { Observable } from 'rxjs';
import { Observable, Subscription } from 'rxjs';
import { isNotEmptyStr } from '@core/utils';
import {
TbLatestDataLayerItem,
@ -23,6 +24,8 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
private circle: L.Circle;
private circleStyleInfo: ShapeStyleInfo;
private styleSubscription: Subscription;
private geometryDirty = false;
private editing = false;
constructor(data: FormattedData<TbMapDatasource>,
@ -41,6 +44,7 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
}
public remove() {
this.styleSubscription?.unsubscribe();
super.remove();
if (this.circleStyleInfo?.patternId) {
this.dataLayer.getMap().unUseShapePattern(this.circleStyleInfo.patternId);
@ -56,7 +60,7 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
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;
if (this.circle) {
this.circle.setStyle(this.circleStyleInfo.style);
@ -77,12 +81,16 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
}
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.updateCircleShape(data);
const geometryChanged = this.updateCircleShape(data);
this.updateTooltip(data, dsData);
this.updateLabel(data, dsData);
this.circle.setStyle(this.circleStyleInfo.style);
this.updateLabel(data, dsData, geometryChanged);
if (styleChanged) {
this.circle.setStyle(this.circleStyleInfo.style);
}
});
}
@ -154,20 +162,28 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem<CirclesDataLayerSettin
const center = this.circle.getLatLng();
const radius = this.circle.getRadius();
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) {
return;
this.markDataStale();
return false;
}
let changed = this.geometryDirty;
this.geometryDirty = false;
const circleData = this.dataLayer.extractCircleCoordinates(data);
const center = new L.LatLng(circleData.latitude, circleData.longitude);
if (!this.circle.getLatLng().equals(center)) {
this.circle.setLatLng(center);
changed = true;
}
if (this.circle.getRadius() !== 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-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
DataLayerTooltipSettings,
DataLayerTooltipTrigger, processTooltipTemplate,
@ -10,6 +11,14 @@ import { FormattedData } from '@shared/models/widget.models';
import L from 'leaflet';
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>,
layer: L.Layer,
settings: DataLayerTooltipSettings,
@ -17,6 +26,13 @@ export const createTooltip = (map: TbMap<any>,
canOpen: () => boolean): L.Popup => {
const tooltip = L.popup({autoClose: settings.autoclose, closeOnClick: false});
(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) => {
tooltip.setLatLng((e as any).latlng);
});
@ -29,18 +45,13 @@ export const createTooltip = (map: TbMap<any>,
if (tooltip.isOpen()) {
tooltip.close();
} else if (canOpen()) {
if ((tooltip as any)._prepareOpen((layer as any)._latlng)) {
map.deselectItem();
tooltip.openOn(map.getMap());
}
open(() => map.deselectItem());
}
});
} else if (settings.trigger === DataLayerTooltipTrigger.hover) {
layer.on('mouseover', () => {
if (canOpen()) {
if ((tooltip as any)._prepareOpen((layer as any)._latlng)) {
tooltip.openOn(map.getMap());
}
open();
}
});
layer.on('mousemove', (e) => {
@ -51,7 +62,7 @@ export const createTooltip = (map: TbMap<any>,
});
}
layer.on('popupopen', () => {
bindTooltipActions(map, tooltip, settings, data);
bindTooltipActions(map, tooltip, settings, tooltipStates.get(tooltip)?.data ?? data);
});
return tooltip;
}
@ -62,12 +73,26 @@ export const updateTooltip = (map: TbMap<any>,
processor: DataLayerPatternProcessor,
data: FormattedData<TbMapDatasource>,
dsData: FormattedData<TbMapDatasource>[]): void => {
let tooltipTemplate = processor.processPattern(data, dsData);
tooltipTemplate = processTooltipTemplate(tooltipTemplate);
tooltip.setContent(tooltipTemplate);
if (tooltip.isOpen() && tooltip.getElement()) {
bindTooltipActions(map, tooltip, settings, data);
tooltipStates.set(tooltip, {processor, data, content: tooltipStates.get(tooltip)?.content});
if (tooltip.isOpen()) {
if (renderTooltip(tooltip, dsData) && tooltip.getElement()) {
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 => {
@ -80,7 +105,7 @@ const bindTooltipActions = (map: TbMap<any>, tooltip: L.Popup, settings: DataLay
if (action) {
element.onclick = ($event) =>
{
map.dataItemClick($event, action, data);
map.dataItemClick($event, action, tooltipStates.get(tooltip)?.data ?? data);
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-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
DataLayerEditAction,
MapDataLayerSettings,
@ -12,12 +13,25 @@ import L from 'leaflet';
import { createTooltip, updateTooltip } from './data-layer-utils';
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,
D extends TbLatestMapDataLayer<S,D> = TbLatestMapDataLayer<any>, L extends L.Layer = L.Layer> extends TbDataLayerItem<S,D,L> {
protected tooltip: L.Popup;
protected labelContent: string;
protected data: FormattedData<TbMapDatasource>;
protected selected = false;
private dataStale = false;
protected constructor(data: 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.bindEvents();
}
public onAddedToContainer(): void {
try {
this.dataLayer.getDataLayerContainer().addLayer(this.layer);
this.editModeUpdated();
} catch (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 {
this.data = data;
this.doUpdate(data, dsData);
public update(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): boolean {
if (!this.dataStale && this.dataLayer.canSkipUnchangedItems() && isSameFormattedData(this.data, data)) {
return false;
} else {
this.dataStale = false;
this.data = data;
this.doUpdate(data, dsData);
return true;
}
}
public remove() {
@ -130,6 +152,15 @@ export abstract class TbLatestDataLayerItem<S extends MapDataLayerSettings = Map
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 {
if (this.dataLayer.isSelectable()) {
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) {
this.unbindLabel();
const label = this.dataLayer.dataLayerLabelProcessor.processPattern(data, dsData);
const labelColor = this.dataLayer.getCtx().widgetConfig.color;
const content: L.Content = `<div style="color: ${labelColor};"><b>${label}</b></div>`;
this.bindLabel(content);
const content = this.createLabelContent(data, dsData);
if (force || content !== this.labelContent) {
this.unbindLabel();
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 {
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 toDelete = new Set(Array.from(this.layerItems.keys()));
const updatedItems: TbLatestDataLayerItem<S,D,L>[] = [];
const createdItems: TbLatestDataLayerItem<S,D,L>[] = [];
layerData.forEach((data) => {
if (this.isValidLayerData(data)) {
let layerItem = this.layerItems.get(data.entityId);
if (layerItem) {
layerItem.update(data, dsData);
updatedItems.push(layerItem);
if (layerItem.update(data, dsData)) {
updatedItems.push(layerItem);
}
} else {
layerItem = this.createLayerItem(data, dsData);
this.layerItems.set(data.entityId, layerItem);
createdItems.push(layerItem);
}
toDelete.delete(data.entityId);
} else {
@ -332,6 +373,9 @@ export abstract class TbLatestMapDataLayer<S extends MapDataLayerSettings = MapD
toDelete.forEach((key) => {
this.removeItem(key);
});
if (createdItems.length) {
this.addItemsToContainer(createdItems);
}
if (updatedItems.length) {
this.layerItemsUpdated(updatedItems);
}
@ -388,6 +432,7 @@ export abstract class TbLatestMapDataLayer<S extends MapDataLayerSettings = MapD
this.unplacedItems.splice(index, 1);
const layerItem = this.createLayerItem(unplacedItem.entity, this.map.getData());
this.layerItems.set(unplacedItem.entity.entityId, layerItem);
this.addItemsToContainer([layerItem]);
this.map.enabledDataLayersUpdated();
}
}
@ -395,6 +440,18 @@ export abstract class TbLatestMapDataLayer<S extends MapDataLayerSettings = MapD
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[] {
const div = document.createElement('div');
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
} from '@shared/models/widget/maps/map.models';
import {
createLabelFromPattern,
fillDataPattern,
guid,
isDefined,
isDefinedAndNotNull,
@ -28,21 +28,79 @@ import L from 'leaflet';
import { CompiledTbFunction } from '@shared/models/js-function.models';
import { forkJoin, Observable, of } from 'rxjs';
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 { TbMap } from '@home/components/widget/lib/maps/map';
import { WidgetContext } from '@home/models/widget-component.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 {
private static readonly PARSED_PATTERN_CACHE_SIZE = 100;
private patternFunction: CompiledTbFunction<MapStringFunction>;
private pattern: string;
private customTranslate: CustomTranslatePipe;
private parsedPatterns = new Map<string, ParsedPatternVariable[]>();
constructor(private dataLayer: TbMapDataLayer,
private settings: DataLayerPatternSettings) {}
public setup(): Observable<void> {
this.customTranslate = this.dataLayer.getCtx().$injector.get(CustomTranslatePipe);
if (this.settings.type === DataLayerPatternType.function) {
return parseTbFunction<MapStringFunction>(this.dataLayer.getCtx().http, this.settings.patternFunction, ['data', 'dsData', 'ctx']).pipe(
map((parsed) => {
@ -63,9 +121,31 @@ export class DataLayerPatternProcessor {
} else {
pattern = this.pattern;
}
const text = createLabelFromPattern(pattern, data);
const customTranslate = this.dataLayer.getCtx().$injector.get(CustomTranslatePipe);
return customTranslate.transform(text);
const replaceInfo: ReplaceInfo[] = [];
for (const v of this.getParsedPattern(pattern)) {
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 itemsUseAdditionalData: boolean;
public dataLayerLabelProcessor: DataLayerPatternProcessor;
public dataLayerTooltipProcessor: DataLayerPatternProcessor;
protected constructor(protected map: TbMap<any>,
inputSettings: S) {
this.settings = mergeDeepIgnoreArray({} as S, this.defaultBaseSettings(map) as S, inputSettings);
this.itemsUseAdditionalData = settingsUseAdditionalData(this.settings);
if (this.settings.groups?.length) {
this.settings.groups.forEach((group) => {
this.groupsState[group] = true;
@ -222,6 +305,10 @@ export abstract class TbMapDataLayer<S extends MapDataLayerSettings = MapDataLay
this.layerItems.forEach(item => item.invalidateCoordinates());
}
public canSkipUnchangedItems(): boolean {
return !this.itemsUseAdditionalData;
}
public getCtx(): WidgetContext {
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';
import L, { FeatureGroup } from 'leaflet';
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 {
deepClone,
isDefined,
isDefinedAndNotNull,
isEmptyStr,
isEqual,
parseTbFunction, plainColorFromVariable,
safeExecuteTbFunction
} from '@core/utils';
import { catchError, map, switchMap } from 'rxjs/operators';
import { catchError, map, shareReplay, switchMap } from 'rxjs/operators';
import tinycolor from 'tinycolor2';
import { ImagePipe } from '@shared/pipe/image.pipe';
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> {
private static readonly MARKER_ICON_CACHE_SIZE = 256;
private positionFunction: CompiledTbFunction<MarkerPositionFunction>;
private markerIconProcessor: MarkerIconProcessor<any>;
private markerIconCache = new Map<string, MarkerIconInfo>();
private markerAssetCache = new Map<string, Observable<unknown>>();
constructor(public dataLayer: TbMapDataLayer,
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> {
return createColorMarkerShapeURI(this.dataLayer.getCtx().$injector.get(MatIconRegistry), this.dataLayer.getCtx().$injector.get(DomSanitizer), shape, color).pipe(
map((iconUrl) => {
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
}
})
);
const assetKey = `shape|${shape}|${color.toHex8()}`;
return this.cachedMarkerIcon(assetKey, rotationAngle, size,
() => createColorMarkerShapeURI(this.dataLayer.getCtx().$injector.get(MatIconRegistry),
this.dataLayer.getCtx().$injector.get(DomSanitizer), shape, color),
(iconUrl: string) => this.buildColoredMarkerShape(iconUrl, rotationAngle, size));
}
public createColoredMarkerIcon(iconContainer: MarkerIconContainer,
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),
iconContainer, icon, color).pipe(
map((element) => {
if (rotationAngle !== 0) {
element.style.transform = `rotate(${rotationAngle}deg)`;
}
return {
size: [size, size],
icon: L.divIcon({
html: element.outerHTML,
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]]
})
};
const assetKey = `icon|${iconContainer}|${icon}|${color.toHex8()}`;
return this.cachedMarkerIcon(assetKey, rotationAngle, size,
() => createColorMarkerIconElement(this.dataLayer.getCtx().$injector.get(MatIconRegistry),
this.dataLayer.getCtx().$injector.get(DomSanitizer), iconContainer, icon, color),
(element: SVGElement) => this.buildColoredMarkerIcon(element, rotationAngle, size));
}
private cachedMarkerIcon<T>(assetKey: string, rotationAngle: number, size: number,
loadAsset: () => Observable<T>,
buildIcon: (asset: T) => MarkerIconInfo): Observable<MarkerIconInfo> {
const iconKey = `${assetKey}|${size}`;
const cachedIcon = rotationAngle === 0 ? this.lruGet(this.markerIconCache, iconKey) : undefined;
let result: Observable<MarkerIconInfo>;
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> {
private marker: L.Marker;
private labelOffset: L.PointTuple;
private boundLabelOffset: L.PointTuple;
private appliedIconInfo: MarkerIconInfo;
private iconClassList: string[];
private moving = false;
private markerIconSubscription: Subscription;
private dragStart: () => void;
private dragEnd: () => void;
@ -401,12 +489,18 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem<MarkersDataLayerSettin
this.marker.options.bubblingMouseEvents = !this.dataLayer.isEditMode();
}
public remove() {
this.markerIconSubscription?.unsubscribe();
super.remove();
}
protected create(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): L.Marker {
this.iconClassList = [];
const location = this.dataLayer.dataProcessor.extractLocation(data, dsData);
this.dragStart = this._dragStart.bind(this);
this.dragEnd = this._dragEnd.bind(this);
this.marker = L.marker(location, {
icon: createPlaceholderMarkerIcon(),
tbMarkerData: data,
snapIgnore: !this.dataLayer.isSnappable(),
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 });
}
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 {
this.marker.options.tbMarkerData = data;
this.updateMarkerLocation(data, dsData);
@ -501,6 +612,7 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem<MarkersDataLayerSettin
private saveMarkerLocation() {
const location = this.marker.getLatLng();
this.dataLayer.saveMarkerLocation(this.data, location).subscribe();
this.markDataStale();
}
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>[]) {
this.dataLayer.dataProcessor.createMarkerIcon(data, dsData).subscribe(
this.markerIconSubscription?.unsubscribe();
this.markerIconSubscription = this.dataLayer.dataProcessor.createMarkerIcon(data, dsData).subscribe(
(iconInfo) => {
let icon: L.Icon | L.DivIcon;
const options = deepClone(iconInfo.icon.options);
options.className = this.updateIconClasses(options.className);
if (iconInfo.icon instanceof L.DivIcon) {
icon = L.divIcon(options);
} else {
icon = L.icon(options as L.IconOptions);
}
this.marker.setIcon(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];
if (!isSameMarkerIcon(this.appliedIconInfo, iconInfo)) {
let icon: L.Icon | L.DivIcon;
const options = deepClone(iconInfo.icon.options);
options.className = this.updateIconClasses(options.className);
if (iconInfo.icon instanceof L.DivIcon) {
icon = L.divIcon(options);
} else {
icon = L.icon(options as L.IconOptions);
}
this.marker.setIcon(icon);
this.appliedIconInfo = iconInfo;
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.editModeUpdated();
}
this.updateLabel(data, dsData);
this.editModeUpdated();
}
);
}
@ -562,6 +678,8 @@ export class TbMarkersDataLayer extends TbLatestMapDataLayer<MarkersDataLayerSet
public tooltipOffset: L.LatLngTuple;
private markersClusterContainer: L.MarkerClusterGroup;
private pendingClusterLayers = new Set<L.Layer>();
private removedPendingClusterLayers = new Set<L.Layer>();
private clusterMarkerColorFunction: CompiledTbFunction<ClusterMarkerColorFunction>;
private readonly markersPane: string;
@ -679,6 +797,54 @@ export class TbMarkersDataLayer extends TbLatestMapDataLayer<MarkersDataLayerSet
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 {
const markerClusterOptions: L.MarkerClusterGroupOptions = {
spiderfyOnMaxZoom: this.settings.markerClustering?.spiderfyOnMaxZoom,
@ -729,6 +895,7 @@ export class TbMarkersDataLayer extends TbLatestMapDataLayer<MarkersDataLayerSet
markerClusterOptions.disableClusteringAtZoom = Math.floor(this.settings.markerClustering.maxZoom);
}
this.markersClusterContainer = new L.MarkerClusterGroup(markerClusterOptions);
this.markersClusterContainer.on('layeradd', (e: L.LayerEvent) => this.onClusterLayerAdded(e.layer));
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-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
defaultBasePolygonsDataLayerSettings,
isCutPolygon, isJSON, MapDataLayerType,
@ -8,9 +9,9 @@ import {
} from '@shared/models/widget/maps/map.models';
import L from 'leaflet';
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 { Observable } from 'rxjs';
import { Observable, Subscription } from 'rxjs';
import { isNotEmptyStr, isString } from '@core/utils';
import {
TbLatestDataLayerItem,
@ -23,7 +24,10 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
private polygonContainer: L.FeatureGroup;
private polygon: L.Polygon;
private polygonStyleInfo: ShapeStyleInfo;
private styleSubscription: Subscription;
private appliedGeometryKey: string;
private editing = false;
private pendingGeometryUpdate = false;
constructor(data: FormattedData<TbMapDatasource>,
dsData: FormattedData<TbMapDatasource>[],
@ -41,6 +45,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
}
public remove() {
this.styleSubscription?.unsubscribe();
super.remove();
if (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 {
const polyData = this.dataLayer.extractPolygonCoordinates(data);
this.appliedGeometryKey = this.geometryKey(data);
const polyConstructor = isCutPolygon(polyData) || polyData.length !== 2 ? L.polygon : L.rectangle;
this.polygon = polyConstructor(polyData as (TbPolygonRawCoordinates & L.LatLngTuple[]), {
noClip: true,
@ -56,7 +62,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
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;
if (this.polygon) {
this.polygon.setStyle(this.polygonStyleInfo.style);
@ -80,19 +86,21 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
}
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.updatePolygonShape(data);
const geometryChanged = this.updatePolygonShape(data);
this.updateTooltip(data, dsData);
this.updateLabel(data, dsData);
if (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled()) {
this.updateLabel(data, dsData, geometryChanged);
if (styleChanged && (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled())) {
this.polygon.setStyle(this.polygonStyleInfo.style);
}
});
}
protected doInvalidateCoordinates(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void {
this.updatePolygonShape(data);
this.updatePolygonShape(data, true);
this.updateLabel(data, dsData);
}
@ -130,6 +138,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
protected disableDrag(): void {
this.polygon.pm.disableLayerDrag();
this.polygon.off('pm:dragstart');
this.polygon.off('pm:drag');
this.polygon.off('pm:dragend');
}
@ -292,6 +301,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
const map = this.dataLayer.getMap().getMap();
map.pm.disableGlobalCutMode();
cutButton?.setActive(false);
this.applyPendingGeometryUpdate();
}
private enablePolygonRotateMode(rotateButton?: L.TB.ToolbarButton) {
@ -314,6 +324,14 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
this.polygon.off('pm:rotateend');
this.polygon.off('pm:rotatedisable');
rotateButton?.setActive(false);
this.applyPendingGeometryUpdate();
}
private applyPendingGeometryUpdate() {
if (this.pendingGeometryUpdate) {
this.pendingGeometryUpdate = false;
this.reapplyData();
}
}
private savePolygonCoordinates() {
@ -329,12 +347,27 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
}
}
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) {
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;
if (isCutPolygon(polyData) || polyData.length !== 2) {
if (this.polygon instanceof L.Rectangle) {
@ -354,6 +387,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem<PolygonsDataLayerSett
const bounds = new L.LatLngBounds(polyData as L.LatLngTuple[]);
(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-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
defaultBasePolylinesDataLayerSettings,
isCutPolygon,
@ -13,9 +14,9 @@ import {
} from '@shared/models/widget/maps/map.models';
import L from 'leaflet';
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 { Observable } from 'rxjs';
import { Observable, Subscription } from 'rxjs';
import { isNotEmptyStr, isString } from '@core/utils';
import {
TbLatestDataLayerItem,
@ -28,7 +29,10 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
private polylineContainer: L.FeatureGroup;
private polyline: L.Polyline;
private polylineStyleInfo: ShapeStyleInfo;
private styleSubscription: Subscription;
private appliedGeometryKey: string;
private editing = false;
private pendingGeometryUpdate = false;
constructor(data: FormattedData<TbMapDatasource>,
dsData: FormattedData<TbMapDatasource>[],
@ -46,6 +50,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
}
public remove() {
this.styleSubscription?.unsubscribe();
super.remove();
if (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 {
const polyData = this.dataLayer.extractPolylineCoordinates(data);
this.appliedGeometryKey = this.geometryKey(data);
const polyConstructor = L.polyline;
this.polyline = polyConstructor(polyData as (TbPolylineRawCoordinates & L.LatLngTuple[]), {
noClip: true,
@ -61,7 +67,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
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;
if (this.polyline) {
this.polyline.setStyle(this.polylineStyleInfo.style);
@ -85,20 +91,23 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
}
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.updatePolylineShape(data);
const geometryChanged = this.updatePolylineShape(data);
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);
}
});
}
protected doInvalidateCoordinates(data: FormattedData<TbMapDatasource>, _dsData: FormattedData<TbMapDatasource>[]): void {
this.updatePolylineShape(data);
protected doInvalidateCoordinates(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]): void {
this.updatePolylineShape(data, true);
this.updateLabel(data, dsData);
}
protected addItemClass(clazz: string): void {
@ -135,6 +144,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
protected disableDrag(): void {
this.polyline.pm.disableLayerDrag();
this.polyline.off('pm:dragstart');
this.polyline.off('pm:drag');
this.polyline.off('pm:dragend');
}
@ -312,6 +322,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
const map = this.dataLayer.getMap().getMap();
map.pm.disableGlobalCutMode();
cutButton?.setActive(false);
this.applyPendingGeometryUpdate();
}
private enablePolylineRotateMode(rotateButton?: L.TB.ToolbarButton) {
@ -334,6 +345,14 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
this.polyline.off('pm:rotateend');
this.polyline.off('pm:rotatedisable');
rotateButton?.setActive(false);
this.applyPendingGeometryUpdate();
}
private applyPendingGeometryUpdate() {
if (this.pendingGeometryUpdate) {
this.pendingGeometryUpdate = false;
this.reapplyData();
}
}
private savePolylineCoordinates() {
@ -349,12 +368,27 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem<PolylinesDataLayerSe
}
}
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) {
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;
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.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-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
DataLayerColorSettings,
loadImageWithAspect,
@ -61,6 +62,21 @@ export interface ShapeStyleInfo {
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> {
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,
findRotationAngle,
interpolateLineSegment,
MapDataLayerType, MarkerType,
MapBooleanFunction,
MapDataLayerType, MarkerIconInfo, MarkerType,
TbMapDatasource,
TripsDataLayerSettings
} 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 { map } from 'rxjs/operators';
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 { DataKeyType } from '@shared/models/telemetry/telemetry.models';
import moment from 'moment/moment';
@ -27,7 +28,13 @@ import {
TbDataLayerItem,
TbMapDataLayer
} 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>};
@ -39,13 +46,19 @@ export interface PointItem {
class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsDataLayer, L.FeatureGroup> {
private tripRouteData: TripRouteData;
private timePoints: number[];
private marker: L.Marker;
private markerTooltip: L.Popup;
private markerIconSubscription: Subscription;
private appliedIconInfo: MarkerIconInfo;
private labelOffset: L.PointTuple;
private labelContent: string;
private boundLabelOffset: L.PointTuple;
private polyline: L.Polyline;
private polylineDecorator: L.PolylineDecorator;
private appliedPathColor: string;
private pointsContainer: L.FeatureGroup;
private points = new Map<string, PointItem>();
@ -102,7 +115,7 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
if (this.latestData) {
this.pointData = {...this.pointData, ...this.latestData};
}
this.updatePath();
this.updatePathAppearance();
this.updateMarker();
}
@ -114,6 +127,7 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
}
public remove() {
this.markerIconSubscription?.unsubscribe();
if (this.marker) {
this.layer.removeLayer(this.marker);
this.marker.off();
@ -125,11 +139,9 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
this.layer.off();
}
public calculateAnchors(): number[] {
const entries = Object.entries(this.tripRouteData);
const dsData = this.dataLayer.getMap().getData();
return entries.filter(data => this.dataLayer.getMap().getLocationSnapFilterFunction().execute(data[1], dsData))
.map(data => parseInt(data[0], 10));
public calculateAnchors(snapFilter: CompiledTbFunction<MapBooleanFunction>,
dsData: FormattedData<TbMapDatasource>[]): number[] {
return this.timePoints.filter(time => snapFilter.execute(this.tripRouteData[time], dsData));
}
private create() {
@ -157,6 +169,7 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
return;
}
this.marker = L.marker(location, {
icon: createPlaceholderMarkerIcon(),
tbMarkerData: this.pointData,
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.addTo(this.layer);
}
this.appliedPathColor = pathStyle.color;
}
}
@ -302,24 +316,37 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
if (this.settings.showPath) {
const dsData = this.dataLayer.getMap().getData();
const pathStyle = this.dataLayer.getPathStyle(this.pointData, dsData);
this.polyline.setStyle(pathStyle);
if (this.settings.usePathDecorator) {
this.polylineDecorator.setPatterns(this.dataLayer.getPathDecoratorStyle(pathStyle.color).patterns)
if (pathStyle.color !== this.appliedPathColor) {
this.polyline.setStyle(pathStyle);
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>[]) {
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) => {
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];
if (!isSameMarkerIcon(this.appliedIconInfo, iconInfo)) {
const rotatedElement = this.marker.getElement()?.firstElementChild as HTMLElement;
if (rotatedElement && isRotationOnlyIconChange(this.appliedIconInfo, iconInfo)) {
rotatedElement.style.transform = `rotate(${data.rotationAngle}deg)`;
this.marker.options.icon = iconInfo.icon;
} else {
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);
}
@ -329,11 +356,20 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
private updateMarkerLabel(data: FormattedData<TbMapDatasource>, dsData: FormattedData<TbMapDatasource>[]) {
if (this.settings.label.show) {
this.marker.unbindTooltip();
const label = this.dataLayer.dataLayerLabelProcessor.processPattern(data, dsData);
const labelColor = this.dataLayer.getCtx().widgetConfig.color;
const content: L.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 content = `<div style="color: ${labelColor};"><b>${label}</b></div>`;
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);
result[timeStamp[timeStamp.length - 1]].rotationAngle += findRotationAngle(startPoint, endPoint);
}
this.timePoints = timeStamp.map(Number).sort((a, b) => a - b);
return result;
}
@ -394,19 +431,17 @@ class TbTripDataItem extends TbDataLayerItem<TripsDataLayerSettings, TbTripsData
this.currentTime = this.dataLayer.getMap().getCurrentTime();
let currentPosition = this.tripRouteData[this.currentTime];
if (!currentPosition) {
const timePoints = Object.keys(this.tripRouteData).map(item => parseInt(item, 10));
for (let i = 1; i < timePoints.length; i++) {
if (timePoints[i - 1] < this.currentTime && timePoints[i] > this.currentTime) {
const beforePosition = this.tripRouteData[timePoints[i - 1]];
const afterPosition = this.tripRouteData[timePoints[i]];
const ratio = calculateInterpolationRatio(timePoints[i - 1], timePoints[i], this.currentTime);
currentPosition = {
...beforePosition,
time: this.currentTime,
...interpolateLineSegment(beforePosition, afterPosition, this.settings.xKey.label, this.settings.yKey.label, ratio)
};
break;
}
const timePoints = this.timePoints;
const i = this.findLastTimePointBefore(this.currentTime);
if (i >= 0 && i + 1 < timePoints.length && timePoints[i + 1] > this.currentTime) {
const beforePosition = this.tripRouteData[timePoints[i]];
const afterPosition = this.tripRouteData[timePoints[i + 1]];
const ratio = calculateInterpolationRatio(timePoints[i], timePoints[i + 1], this.currentTime);
currentPosition = {
...beforePosition,
time: this.currentTime,
...interpolateLineSegment(beforePosition, afterPosition, this.settings.xKey.label, this.settings.yKey.label, ratio)
};
}
}
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> {
@ -430,7 +481,7 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
public pointTooltipProcessor: DataLayerPatternProcessor;
private rawTripsData: FormattedData<TbMapDatasource>[][];
private latestTripsData: FormattedData<TbMapDatasource>[];
private latestTripsDataByEntity = new Map<string, FormattedData<TbMapDatasource>>();
constructor(protected map: TbMap<any>,
inputSettings: TripsDataLayerSettings) {
@ -451,7 +502,7 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
this.rawTripsData =
tripsData.filter(d => !!d.length && d[0].$datasource.mapDataIds.includes(this.mapDataId)).map(
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) => {
minTime = Math.min(dataSource[0].time, minTime);
maxTime = Math.max(dataSource[dataSource.length - 1].time, maxTime);
@ -467,7 +518,7 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
if (tripItem) {
tripItem.update(rawTripData);
} else {
const latestData = this.latestTripsData.find(d => d.entityId === entityId);
const latestData = this.latestTripsDataByEntity.get(entityId);
tripItem = new TbTripDataItem(rawTripData, latestData, this.settings, this);
this.layerItems.set(entityId, tripItem);
}
@ -479,10 +530,9 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
}
public updateTripsLatestData(tripsLatestData: FormattedData<TbMapDatasource>[]) {
this.latestTripsData = tripsLatestData.filter(d => d.$datasource.mapDataIds.includes(this.mapDataId));
this.setLatestTripsData(tripsLatestData);
this.layerItems.forEach((item, entityId) => {
const latestData = this.latestTripsData.find(d => d.entityId === entityId);
item.updateLatestData(latestData);
item.updateLatestData(this.latestTripsDataByEntity.get(entityId));
});
}
@ -499,12 +549,13 @@ export class TbTripsDataLayer extends TbMapDataLayer<TripsDataLayerSettings, TbT
}
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 => {
const tripAnchors = item.calculateAnchors();
anchors = [...new Set([...anchors, ...tripAnchors])];
item.calculateAnchors(snapFilter, dsData).forEach(anchor => anchors.add(anchor));
});
return anchors;
return [...anchors];
}
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));
}
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>[] {
const firstValidIndex = dataSource.findIndex(this.hasValidLocation);
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 'leaflet-providers';
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 'leaflet.markercluster';
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);
// 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 {
@ -1107,11 +1111,13 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
private _offset: L.Point;
private _zooming: boolean;
private _glError = false;
private _ownMaxBounds: L.LatLngBounds;
private _prevMaxBoundsViscosity: number;
constructor(options: TB.MapLibreGL.LeafletMapLibreGLMapOptions) {
super();
options = {
maxZoom: MAP_LIBRE_GL_DEFAULT_MAX_ZOOM,
maxZoom: mapLibreGlDefaultMaxZoom,
...options,
updateInterval: 32,
padding: 0.1,
@ -1125,28 +1131,26 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
}
beforeAdd(map: L.Map): this {
map._addZoomLimit(this);
if (!this.options.overlay) {
map._addZoomLimit(this);
}
return this;
}
onAdd(map: L.Map): this {
let update = false;
if (!this._container) {
this._initContainer();
} else {
update = true;
}
const paneName = this.getPaneName();
map.getPane(paneName).appendChild(this._container);
this._initGL();
this._limitPan(map);
this._offset = this._map.containerPointToLayerPoint([0, 0]);
if ((this._map as any)._proxy && map.options.zoomAnimation) {
L.DomEvent.on((map as any)._proxy, L.DomUtil.TRANSITION_END, this._transitionEnd, this);
}
if (update) {
this._update();
}
this._update();
return this;
}
@ -1157,6 +1161,7 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
const paneName = this.getPaneName();
map.getPane(paneName).removeChild(this._container);
map._removeZoomLimit(this);
this._releasePan(map);
if (this._glMap) {
this._glMap.remove();
@ -1221,13 +1226,16 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer {
}
private _initGL() {
const center = this._map.getCenter();
const options = L.extend({}, this.options, {
container: this._container,
center: [center.lng, center.lat],
center: this._getGLCenter(),
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;
try {
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),
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) {
container.style.width = size.x + 'px';
container.style.height = size.y + 'px';
gl.resize();
}
this._transformGL(gl);
L.DomUtil.setPosition(container, this._roundPoint(topLeft.add([0, this._getGLCenterOffsetY()])));
}
private _transformGL(gl: MapLibreGLMap) {
const center = this._map.getCenter();
gl.jumpTo({
center: [center.lng, center.lat],
center: this._getGLCenter(),
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() {
if (!this._glReady()) { return; }
this._glMap.jumpTo({
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(() => {
if (!this._glReady()) { return; }
const zoom = this._map.getZoom();
const center = this._map.getCenter();
const center = this._getGLCenter();
const offset = this._map.latLngToContainerPoint(
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({
style: this.referenceLayerStyle(spec),
// The reference layer is drawn over a raster base, so the base layer's zoom limit applies
maxZoom: undefined
overlay: true
});
})
);

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 { TbTripsDataLayer } from '@home/components/widget/lib/maps/data-layer/trips-data-layer';
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 { 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';
@ -122,6 +122,7 @@ export abstract class TbMap<S extends BaseMapSettings> {
protected timeLineComponentRef: ComponentRef<MapTimelinePanelComponent>;
protected timeLineComponent: MapTimelinePanelComponent;
protected locationSnapFilterFunction: CompiledTbFunction<MapBooleanFunction>;
private locationSnapFilterUsesAdditionalData = false;
protected addMarkerDataLayers: TbLatestMapDataLayer<any>[];
protected addPolygonDataLayers: TbLatestMapDataLayer<any>[];
@ -223,6 +224,7 @@ export abstract class TbMap<S extends BaseMapSettings> {
}
const setup = [this.doSetupControls()];
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(
map((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]);
this.latestDataLayers.forEach(dl => dl.updateData(this.dsData));
this.updateTripsAppearance();
this.updateTripsAnchors();
if (this.locationSnapFilterUsesAdditionalData) {
this.updateTripsAnchors();
}
this.updateBounds();
this.updateEditButtonsStates();
this.ctx.updateLabelPatterns();
@ -1010,7 +1014,7 @@ export abstract class TbMap<S extends BaseMapSettings> {
}
private updateTripsAppearance() {
this.tripDataLayers.forEach(dl => dl.updateAppearance());
this.tripDataLayers.filter(dl => !dl.canSkipUnchangedItems()).forEach(dl => dl.updateAppearance());
}
private updateTripsTime() {
@ -1021,13 +1025,12 @@ export abstract class TbMap<S extends BaseMapSettings> {
if (this.timeline) {
if (this.settings.tripTimeline.snapToRealLocation) {
// Recalculate anchors only for enabled layers
let anchors: number[] = [];
const anchorSet = new Set<number>();
const enableTrips = this.tripDataLayers.filter(dl => dl.isEnabled());
for (const tripsDataLayer of enableTrips) {
const tripsAnchors = tripsDataLayer.calculateAnchors();
anchors = [...new Set([...anchors, ...tripsAnchors])];
tripsDataLayer.calculateAnchors().forEach(anchor => anchorSet.add(anchor));
}
anchors.sort((a, b) => a - b);
const anchors = [...anchorSet].sort((a, b) => a - b);
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 { TbFunction } from '@shared/models/js-function.models';
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 { MarkerIconContainer, MarkerShape } from '@shared/models/widget/maps/marker-shape.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 imageAspectLoading: {[key: string]: Observable<ImageWithAspect>} = {};
const imageLoader = (imageUrl: string): Observable<HTMLImageElement> => new Observable((observer: Observer<HTMLImageElement>) => {
const image = document.createElement('img'); // support IE
const measureAttachedImage = (image: HTMLImageElement): [number, number] => {
image.style.position = 'absolute';
image.style.left = '-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);
image.src = imageUrl;
});
const size: [number, number] = [image.width, image.height];
image.remove();
return size;
};
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 {
url: string;
@ -1592,32 +1604,37 @@ export interface ImageWithAspect {
}
export const loadImageWithAspect = (imagePipe: ImagePipe, imageUrl: string): Observable<ImageWithAspect> => {
if (imageUrl?.length) {
const hash = hashCode(imageUrl);
let imageWithAspect = imageAspectMap[hash];
if (imageWithAspect) {
return of(imageWithAspect);
} else {
return imagePipe.transform(imageUrl, {asString: true, ignoreLoadingImage: true}).pipe(
if (!imageUrl?.length) {
return of(null);
}
const hash = hashCode(imageUrl);
const imageWithAspect = imageAspectMap[hash];
if (imageWithAspect) {
return of(imageWithAspect);
} else {
let loading$ = imageAspectLoading[hash];
if (!loading$) {
loading$ = imagePipe.transform(imageUrl, {asString: true, ignoreLoadingImage: true}).pipe(
switchMap((res) => {
const url = res as string;
return loadImageSize(url).pipe(
map((size) => {
imageWithAspect = {
url,
width: size[0],
height: size[1],
aspect: size[0]/size[1]
};
map(([width, height]) => {
const imageWithAspect: ImageWithAspect = {url, width, height, aspect: width / height};
imageAspectMap[hash] = imageWithAspect;
return imageWithAspect;
})
);
})
}),
finalize(() => {
if (imageAspectLoading[hash] === loading$) {
delete imageAspectLoading[hash];
}
}),
shareReplay({bufferSize: 1, refCount: false})
);
imageAspectLoading[hash] = loading$;
}
} else {
return of(null);
return loading$;
}
};

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"> {
updateInterval?: number;
overlay?: boolean;
padding?: number;
className?: string;
}

Loading…
Cancel
Save