Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Fix map marker flickering when receiving WebSocket events (#2610)

Koen0c431fc59d13
diff --git a/ui/app/manager/src/index.ts b/ui/app/manager/src/index.ts
index 5ff840a63..7b2398de4 100644
--- a/ui/app/manager/src/index.ts
+++ b/ui/app/manager/src/index.ts
@@ -62,7 +62,9 @@ const rootReducer = combineReducers({
type RootState = ReturnType<typeof rootReducer>;
export const store = configureStore({
- reducer: rootReducer
+ reducer: rootReducer,
+ // Disable serializableCheck to improve performance in developement (normally disabled in production)
+ middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: false }),
});
const orApp = new OrApp(store);
diff --git a/ui/app/manager/src/pages/page-map.ts b/ui/app/manager/src/pages/page-map.ts
index de7d49087..4bce78438 100644
--- a/ui/app/manager/src/pages/page-map.ts
+++ b/ui/app/manager/src/pages/page-map.ts
@@ -12,7 +12,8 @@ import {
OrMapGeocoderChangeEvent,
MapMarkerAssetConfig,
OrMapMarkersChangedEvent,
- OrMapLegendEvent
+ OrMapLegendEvent,
+ OrMapLoadedEvent
} from "@openremote/or-map";
import manager, {Util} from "@openremote/core";
import {createSelector} from "reselect";
@@ -32,7 +33,8 @@ import {GenericAxiosResponse} from "@openremote/rest";
import { ClusterConfig, Util as MapUtil, AssetWithLocation } from "@openremote/or-map";
export interface MapState {
- assets: Asset[];
+ locatedAssets: AssetWithLocation[];
+ unlocatedAssets: Asset[];
currentAssetId: string;
}
@@ -41,7 +43,8 @@ export interface MapStateKeyed extends AppStateKeyed {
}
const INITIAL_STATE: MapState = {
- assets: [],
+ locatedAssets: [],
+ unlocatedAssets: [],
currentAssetId: undefined
};
@@ -50,54 +53,70 @@ const pageMapSlice = createSlice({
initialState: INITIAL_STATE,
reducers: {
assetEventReceived(state: MapState, action: PayloadAction<AssetEvent>) {
-
if (action.payload.cause === AssetEventCause.CREATE) {
- // Update and delete handled by attribute handler
-
- const asset = action.payload.asset;
- if (MapUtil.isAssetWithLocation(asset)) {
- return {
- ...state,
- assets: [...state.assets, action.payload.asset]
- };
+ if (MapUtil.isAssetWithLocation(action.payload.asset)) {
+ state.locatedAssets.push(action.payload.asset);
+ } else {
+ state.unlocatedAssets.push(action.payload.asset);
+ }
+ } else if (action.payload.cause === AssetEventCause.DELETE) {
+ const index = state.locatedAssets.findIndex(asset => asset.id === action.payload.asset.id);
+ if (index > -1) state.locatedAssets.splice(index, 1);
+ else {
+ const index = state.unlocatedAssets.findIndex(asset => asset.id === action.payload.asset.id);
+ if (index > -1) state.unlocatedAssets.splice(index, 1);
}
}
-
return state;
},
attributeEventReceived(state: MapState, action: PayloadAction<[string[], AttributeEvent]>) {
- const assets = state.assets;
const attrsOfInterest = action.payload[0];
const attrEvent = action.payload[1];
const attrName = attrEvent.ref.name;
- const assetId = attrEvent.ref.id;
- const index = assets.findIndex((asst) => asst.id === assetId);
- const asset = index >= 0 ? assets[index] : null;
-
- if (!asset) {
- return state;
- }
-
- if (attrName === WellknownAttributes.LOCATION && attrEvent.deleted) {
- return {
- ...state,
- assets: [...assets.splice(index, 1)]
- };
- }
// Only react if attribute is an attribute of interest
if (!attrsOfInterest.includes(attrName)) {
return;
}
- assets[index] = Util.updateAsset({...asset}, attrEvent);
+ const locatedAssets = state.locatedAssets;
+ const unlocatedAssets = state.unlocatedAssets;
+ const assetId = attrEvent.ref.id;
+
+ const located = locatedAssets.findIndex((a) => a.id === assetId);
+ if (located > -1) {
+ const asset = Util.updateAsset({ ...locatedAssets[located] }, attrEvent);
+ if (MapUtil.isAssetWithLocation(asset)) {
+ locatedAssets[located] = asset;
+ } else {
+ locatedAssets.splice(located, 1);
+ unlocatedAssets.push(asset);
+ }
+ } else {
+ const unlocated = unlocatedAssets.findIndex((a) => a.id === assetId);
+ if (unlocated > -1) {
+ const asset = Util.updateAsset({ ...unlocatedAssets[unlocated] }, attrEvent);
+ if (MapUtil.isAssetWithLocation(asset)) {
+ unlocatedAssets.splice(unlocated, 1);
+ locatedAssets.push(asset);
+ } else {
+ unlocatedAssets[unlocated] = asset;
+ }
+ }
+ }
+
return state;
},
setAssets(state, action: PayloadAction<Asset[]>) {
- return {
- ...state,
- assets: action.payload
- };
+ const locatedAssets = [], unlocatedAssets = [];
+ for (const asset of action.payload) {
+ if (MapUtil.isAssetWithLocation(asset)) {
+ locatedAssets.push(asset);
+ } else {
+ unlocatedAssets.push(asset);
+ }
+ }
+ return { ...state, locatedAssets, unlocatedAssets };
}
}
});
@@ -196,32 +215,28 @@ export class PageMap extends Page<MapStateKeyed> {
protected _map?: OrMap;
@state()
- protected _assets: Asset[] = [];
+ protected _assets: AssetWithLocation[] = [];
@state()
protected _currentAsset?: Asset;
+ @state()
+ protected _assetTypes: string[] = [];
+
+ @state()
+ protected _excludedTypes: string[] = [];
+
@state()
protected _assetsOnScreen: AssetWithLocation[] = [];
- protected _assetSelector = (state: MapStateKeyed) => state.map.assets;
+ protected _locatedAssetSelector = (state: MapStateKeyed) => state.map.locatedAssets;
+ protected _unlocatedAssetSelector = (state: MapStateKeyed) => state.map.unlocatedAssets;
protected _paramsSelector = (state: MapStateKeyed) => state.app.params;
protected _realmSelector = (state: MapStateKeyed) => state.app.realm || manager.displayRealm;
protected _assetSubscriptionId: string;
protected _attributeSubscriptionId: string;
- protected _assetTypes: string[] = [];
- protected _excludedTypes: string[] = [];
-
- shouldUpdate(_changedProperties: PropertyValues): boolean {
- if (_changedProperties.has("_assets")) {
- this._updateMarkers();
- this._map?.reload();
- }
- return super.shouldUpdate(_changedProperties);
- }
-
protected getAttributesOfInterest(): (string | WellknownAttributes)[] {
// Extract all label attributes configured in marker config
let markerLabelAttributes = [];
@@ -292,9 +307,18 @@ export class PageMap extends Page<MapStateKeyed> {
const assets = response.data;
this._store.dispatch(setAssets(assets));
+ this._map?.addAssets(this._assets);
const assetSubscriptionId = await manager.events.subscribeAssetEvents(undefined, false, (event) => {
this._store.dispatch(assetEventReceived(event));
+ switch (event.cause) {
+ case "DELETE": this._map?.removeAssets([event.asset.id]); break;
+ case "CREATE":
+ if (MapUtil.isAssetWithLocation(event.asset) && !this._excludedTypes.includes(event.asset?.type)) {
+ this._map?.addAsset(event.asset);
+ }
+ break;
+ }
});
if (!this.isConnected || realm !== this._realmSelector(this.getState())) {
@@ -305,7 +329,22 @@ export class PageMap extends Page<MapStateKeyed> {
this._assetSubscriptionId = assetSubscriptionId;
const attributeSubscriptionId = await manager.events.subscribeAttributeEvents(undefined, false, (event) => {
+ const interested = attrsOfInterest.includes(event.ref.name);
+ let asset: Asset | undefined;
+ if (interested) {
+ const assets = this._unlocatedAssetSelector(this.getState());
+ asset = assets.find(asset => asset.id === event.ref.id);
+ // Update the attribute if the asset already has a location
+ // assuming the asset is in the located asset state
+ if (!asset) {
+ this._map?.updateAttribute(event);
+ }
+ }
this._store.dispatch(attributeEventReceived([attrsOfInterest, event]));
+ // Add the asset after map state has been updated
+ if (interested && asset && !this._excludedTypes.includes(asset.type)) {
+ this._map?.addAsset(this._assets.find(asset => asset.id === event.ref.id));
+ }
});
if (!this.isConnected || realm !== this._realmSelector(this.getState())) {
@@ -331,35 +370,27 @@ export class PageMap extends Page<MapStateKeyed> {
manager.events.unsubscribe(this._attributeSubscriptionId);
this._attributeSubscriptionId = undefined;
}
+ this._map?.removeAllAssets();
};
protected getRealmState = createSelector(
[this._realmSelector],
async (realm) => {
- if (this._assets.length > 0) {
- // Clear existing assets
- this._assets = [];
- }
- if (this._excludedTypes.length > 0) {
- this._excludedTypes = [];
- }
-
+ this._excludedTypes = [];
this.unsubscribeAssets();
- this.subscribeAssets(realm).then(async () => {
- await this._map?.reload();
- });
+ this.subscribeAssets(realm);
this._map?.refresh();
}
)
protected _getMapAssets = createSelector(
- [this._assetSelector],
+ [this._locatedAssetSelector],
(assets) => {
return assets;
});
protected _getCurrentAsset = createSelector(
- [this._assetSelector, this._paramsSelector],
+ [this._locatedAssetSelector, this._paramsSelector],
(assets, params) => {
const currentId = params ? params.id : undefined;
@@ -383,12 +414,23 @@ export class PageMap extends Page<MapStateKeyed> {
this.addEventListener(OrMapAssetCardLoadAssetEvent.NAME, this._onLoadAssetEvent);
}
+ shouldUpdate(_changedProperties: PropertyValues): boolean {
+ if (_changedProperties.has('_assets')) {
+ const newTypes = [];
+ for (const { type } of this._assets) {
+ if (!newTypes.includes(type)) newTypes.push(type);
+ }
+ this._assetTypes = newTypes;
+ }
+ return super.shouldUpdate(_changedProperties);
+ }
+
protected render() {
const showLegend = this.config?.legend?.show !== false && this._assetTypes.length > 1;
return html`
${this._currentAsset ? html `<or-map-asset-card .config="${this.config?.card}" .assetId="${this._currentAsset.id}" .markerconfig="${this.config?.markers}"></or-map-asset-card>` : ``}
- ${showLegend ? html`<or-map-legend .assetTypes="${this._assetTypes}" @or-map-legend-changed="${this._onMapLegendChanged}"></or-map-legend>` : null}
+ ${showLegend ? html`<or-map-legend .assetTypes="${this._assetTypes}" .excludedTypes="${this._excludedTypes}" @or-map-legend-changed="${this._onMapLegendChanged}"></or-map-legend>` : null}
<or-map id="map" class="or-map" .cluster="${this.config.clustering}" showGeoCodingControl @or-map-geocoder-change="${(ev: OrMapGeocoderChangeEvent) => {this._setCenter(ev.detail.geocode);}}">
${this._assetsOnScreen.sort((a,b) => {
@@ -409,6 +451,7 @@ export class PageMap extends Page<MapStateKeyed> {
this.addEventListener(OrMapMarkerClickedEvent.NAME, this._onMapMarkerClick);
this.addEventListener(OrMapClickedEvent.NAME, this._onMapClick);
this.addEventListener(OrMapMarkersChangedEvent.NAME, this._onMapMarkersChanged);
+ this.addEventListener(OrMapLoadedEvent.NAME, this._onMapLoaded);
}
public disconnectedCallback() {
@@ -416,6 +459,7 @@ export class PageMap extends Page<MapStateKeyed> {
this.removeEventListener(OrMapMarkerClickedEvent.NAME, this._onMapMarkerClick);
this.removeEventListener(OrMapClickedEvent.NAME, this._onMapClick);
this.removeEventListener(OrMapMarkersChangedEvent.NAME, this._onMapMarkersChanged);
+ this.removeEventListener(OrMapLoadedEvent.NAME, this._onMapLoaded);
this.unsubscribeAssets();
}
@@ -442,28 +486,24 @@ export class PageMap extends Page<MapStateKeyed> {
router.navigate(getAssetsRoute(false, loadAssetEvent.detail));
}
- protected _onMapLegendChanged(e: OrMapLegendEvent) {
- if (this._map) {
- this._excludedTypes = e.detail;
- this._updateMarkers();
- this._map.reload();
- }
+ protected _onMapLoaded(e: OrMapLoadedEvent) {
+ this._map?.addAssets(this._assets);
}
- protected _updateMarkers() {
+ protected _onMapLegendChanged(e: OrMapLegendEvent) {
if (this._map) {
- this._assetTypes = [];
- this._map.cleanUpAssetMarkers();
- this._assets.forEach((asset: Asset) => {
- if (MapUtil.isAssetWithLocation(asset)) {
- if (!this._excludedTypes.includes(asset.type)) {
- this._map.addAssetMarker(asset)
- }
- if (!this._assetTypes.includes(asset.type)) {
- this._assetTypes.push(asset.type);
- }
+ this._excludedTypes = e.detail;
+ const assetsToAdd = [];
+ const idsToRemove = [];
+ for (const asset of this._assets) {
+ if (this._excludedTypes.includes(asset.type)) {
+ idsToRemove.push(asset.id);
+ } else {
+ assetsToAdd.push(asset);
}
- });
+ }
+ this._map.removeAssets(idsToRemove);
+ this._map.addAssets(assetsToAdd);
}
}
}
diff --git a/ui/app/manager/test/map.test.ts b/ui/app/manager/test/map.test.ts
index 81bf1ef11..d6b09783e 100644
--- a/ui/app/manager/test/map.test.ts
+++ b/ui/app/manager/test/map.test.ts
@@ -311,7 +311,8 @@ test.describe("Marker clustering", () => {
test.skip(browserName === "firefox", "firefox headless mode does not support webgl required by maplibre");
const assetInfos = (await manager.api.AssetModelResource.getAssetInfos()).data;
- const assets = getAssetsForAllTypes(assetInfos);
+ const bbox = { west: 4.4859, south: 51.9163, east: 4.4864, north: 51.9166 };
+ const assets = getAssetsForAllTypes(assetInfos, { bbox });
await manager.setup("smartcity", { assets });
await manager.configureAppConfig({ pages: { map: { clustering: { cluster: false } } } })
diff --git a/ui/component/core/src/util.ts b/ui/component/core/src/util.ts
index a48c6731d..380365ee2 100644
--- a/ui/component/core/src/util.ts
+++ b/ui/component/core/src/util.ts
@@ -969,7 +969,7 @@ function doStandardTranslationLookup(lookup: WellknownMetaItems.LABEL | Wellknow
/**
* Immutable update of an asset using the supplied attribute event
*/
-export function updateAsset(asset: Asset, event: AttributeEvent): Asset {
+export function updateAsset<T extends Asset>(asset: T, event: AttributeEvent): T {
const attributeName = event.ref!.name!;
diff --git a/ui/component/or-dashboard-builder/src/widgets/map-widget.ts b/ui/component/or-dashboard-builder/src/widgets/map-widget.ts
index 8548034a6..808fcead6 100644
--- a/ui/component/or-dashboard-builder/src/widgets/map-widget.ts
+++ b/ui/component/or-dashboard-builder/src/widgets/map-widget.ts
@@ -6,7 +6,7 @@ import {WidgetSettings} from "../util/widget-settings";
import {MapSettings} from "../settings/map-settings";
import {AssetWidgetConfig} from "../util/widget-config";
import {Asset, AssetDescriptor} from "@openremote/model";
-import {LngLatLike, MapMarkerColours, MapMarkerAssetConfig, Util as MapUtil, OrMap, AssetWithLocation, OrMapMarkersChangedEvent, MapMarkerConfig} from "@openremote/or-map";
+import {LngLatLike, MapMarkerColours, MapMarkerAssetConfig, Util as MapUtil, OrMap, AssetWithLocation, OrMapMarkersChangedEvent, MapMarkerConfig, OrMapLoadedEvent} from "@openremote/or-map";
import {map} from "lit/directives/map.js";
import manager from "@openremote/core";
import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
@@ -87,11 +87,13 @@ export class MapWidget extends OrAssetWidget {
}
connectedCallback() {
+ this.addEventListener(OrMapLoadedEvent.NAME, this._onMapLoaded);
this.addEventListener(OrMapMarkersChangedEvent.NAME, this._onMapMarkersChanged);
return super.connectedCallback();
}
disconnectedCallback() {
+ this.removeEventListener(OrMapLoadedEvent.NAME, this._onMapLoaded);
this.removeEventListener(OrMapMarkersChangedEvent.NAME, this._onMapMarkersChanged);
return super.disconnectedCallback();
}
@@ -153,6 +155,12 @@ export class MapWidget extends OrAssetWidget {
`;
}
+ protected _onMapLoaded(e: OrMapLoadedEvent) {
+ const assetType = this.widgetConfig.allOfType ? undefined : this.widgetConfig.assetType;
+ const assets = this.loadedAssets.filter(asset => !assetType || asset.type === assetType).filter(MapUtil.isAssetWithLocation);
+ this._map?.addAssets(assets);
+ }
+
protected _onMapMarkersChanged(e: OrMapMarkersChangedEvent) {
this._assetsOnScreen = e.detail;
}
@@ -196,15 +204,5 @@ export class MapWidget extends OrAssetWidget {
}
this.markers[assetType!] = marker;
}
- // Load the markers onto the map
- if (this._map) {
- this._map.cleanUpAssetMarkers();
- const assetType = this.widgetConfig.allOfType ? undefined : this.widgetConfig.assetType;
- this.loadedAssets
- .filter(asset => MapUtil.isAssetWithLocation(asset) && (!assetType || asset.type === assetType))
- .forEach((asset: Asset) => this._map!.addAssetMarker(asset as AssetWithLocation));
-
- this._map?.reload();
- }
}
}
diff --git a/ui/component/or-map/src/asset-map.ts b/ui/component/or-map/src/asset-map.ts
new file mode 100644
index 000000000..f60ceaa21
--- /dev/null
+++ b/ui/component/or-map/src/asset-map.ts
@@ -0,0 +1,301 @@
+import { CircleLayerSpecification, GeoJSONFeature, GeoJSONSource, MapSourceDataEvent, Marker } from "maplibre-gl";
+import { Feature, Point } from "geojson";
+import { AssetWithLocation, ClusterConfig } from "./types";
+import { BaseMap } from "./base-map";
+import { OrClusterMarker, Slice } from "./markers/or-cluster-marker";
+import { getMarkerIconAndColorFromAssetType } from "./util";
+import { OrMapLoadedEvent, OrMapMarkersChangedEvent } from ".";
+import { Util } from "@openremote/core";
+import { AttributeEvent, WellknownAttributes } from "@openremote/model";
+
+type IdentifiableAsset = AssetWithLocation & { id: string; type: string };
+
+/**
+ * This class handles where to display asset markers and clusters on the map.
+ *
+ * Currently, the standard flow to display assets as markers on the map goes as follows:
+ *
+ * 1. The map page adds assets to the {@link AssetMap}, which computes assets in view and then dispatches {@link OrMapMarkersChangedEvent}.
+ * 2. The map page receives the event, renders the received assets as {@link OrMapMarkerAsset} by including them inside the map element's HTML body.
+ * 3. The map component then receives either an event from the {@link OrMapMarkerAsset},
+ * or when the map component sees a slotted {@link OrMapMarker} was added. From there the {@link OrMapMarker}s are passed to the {@link BaseMap} to be assigned to a MapLibre marker.
+ *
+ * @todo consider using `this._map.setGlobalStateProperty` for static cluster property
+ */
+export class AssetMap extends BaseMap {
+ private static _clusterProperty = "assetType";
+
+ protected _assets: Record<string, AssetWithLocation | null> = {};
+ protected _assetTypeColors: Record<string, string> = {};
+ protected _assetsOnScreen: Record<string, AssetWithLocation> = {};
+ protected _cachedClusters: Record<string, Marker> = {};
+ protected _clustersOnScreen: Record<string, Marker> = {};
+ protected _clusterConfig?: ClusterConfig;
+ protected _source?: GeoJSONSource;
+
+ protected _onMove = () => this._updateMarkers();
+ protected _onMoveEnd = (e: any) => {
+ // Ensure marker updates happen after the frame
+ requestAnimationFrame(() => {
+ // The clicked marker may not be removed,
+ // if the camera zoom level is directly between 2 levels
+ if (e.marker instanceof OrClusterMarker) {
+ this._clustersOnScreen[e.marker._clusterId]?.remove();
+ }
+ this._updateMarkers();
+ });
+ };
+
+ protected _onData = (e: MapSourceDataEvent) => {
+ if (this._map && e.isSourceLoaded && e.sourceId === "assets") {
+ this._map.on("move", this._onMove);
+ this._map.on("moveend", this._onMoveEnd);
+ this._updateMarkers();
+ }
+ };
+
+ constructor(
+ styleParent: Node,
+ mapContainer: HTMLElement,
+ showGeoCodingControl = false,
+ showBoundaryBox = false,
+ useZoomControls = true,
+ showGeoJson = true,
+ clusterConfig?: ClusterConfig
+ ) {
+ super(styleParent, mapContainer, showGeoCodingControl, showBoundaryBox, useZoomControls, showGeoJson);
+ this._clusterConfig = clusterConfig;
+ }
+
+ override async build(): Promise<void> {
+ return super.build().then(() => {
+ this._map?.on("load", async () => await this.load());
+ });
+ }
+
+ /**
+ * Add an asset as (asset) feature to the map.
+ *
+ * Use {@link addAssets} instead if adding multiple assets.
+ * @param asset The asset to add
+ */
+ public addAsset(asset: AssetWithLocation) {
+ if (!this._source) return;
+ const features = this._map!.querySourceFeatures("assets");
+
+ if (!this._hasRequired(asset) || !this._isMissing(asset, features)) {
+ return;
+ }
+
+ if (!(asset.type in this._assetTypeColors)) {
+ this._assetTypeColors[asset.type] = getMarkerIconAndColorFromAssetType(asset.type)?.color as string;
+ this._source.workerOptions.clusterProperties = this._getClusterProperties();
+ }
+
+ this._assets[asset.id] = asset;
+ this._source.updateData({ add: [AssetMap._assetToFeature(asset)] });
+ }
+
+ /**
+ * Add multiple assets as (asset) features to the map. Optimized for adding multiple assets at once.
+ * @param assets The assets to add
+ */
+ public addAssets(assets: AssetWithLocation[]) {
+ if (!this._source) return;
+ const features = this._map!.querySourceFeatures("assets");
+
+ let missing = assets.filter(this._hasRequired);
+ if (features?.length) {
+ missing = missing.filter((a) => this._isMissing(a, features));
+ }
+
+ if (!missing.length) {
+ return;
+ }
+
+ for (const asset of missing) {
+ if (!(asset.type in this._assetTypeColors)) {
+ this._assetTypeColors[asset.type] = getMarkerIconAndColorFromAssetType(asset.type)?.color as string;
+ }
+ this._assets[asset.id] = asset;
+ }
+ this._source.workerOptions.clusterProperties = this._getClusterProperties();
+
+ this._source.updateData({
+ add: missing.map(AssetMap._assetToFeature),
+ });
+ }
+
+ public updateAttribute(event: AttributeEvent) {
+ const id = event?.ref?.id;
+
+ if (!this._source || !id || !this._assets[id]) return;
+
+ if (event.value == null && event.ref?.name === WellknownAttributes.LOCATION) {
+ this._assets[id] = null;
+ this._source?.updateData({ remove: [id] });
+ return;
+ }
+
+ const asset = (this._assets[id] = Util.updateAsset(structuredClone(this._assets[id]), event));
+ const newGeometry = asset.attributes.location.value;
+ const newProperties = Object.entries(AssetMap._assetToFeature(asset as IdentifiableAsset).properties).map(
+ ([key, value]) => ({ key, value })
+ );
+ this._source?.updateData({ update: [{ id, newGeometry, addOrUpdateProperties: newProperties }] });
+ }
+
+ public removeAssets(ids: string[]) {
+ for (const id of ids) this._assets[id] = null;
+ this._source?.updateData({ remove: ids });
+ }
+
+ public removeAllAssets() {
+ this._assets = {};
+ this._source?.updateData({ removeAll: true });
+ }
+
+ /**
+ * Initialize asset sources, layers and data events
+ */
+ private async load() {
+ if (!this._map) {
+ console.warn("MapLibre Map not initialized!");
+ return;
+ }
+
+ if (this._loaded) {
+ return;
+ }
+
+ if (this._map.getSource("assets")) {
+ if (this._map.getLayer("asset")) {
+ this._map.removeLayer("asset");
+ }
+ if (this._map.getLayer("cluster")) {
+ this._map.removeLayer("cluster");
+ }
+ this._map.removeSource("assets");
+ }
+
+ const baseLayer: Omit<CircleLayerSpecification, "id"> = {
+ type: "circle",
+ source: "assets",
+ paint: { "circle-radius": 0 },
+ };
+
+ this._map
+ .addSource("assets", {
+ type: "geojson",
+ cluster: this._clusterConfig?.cluster ?? true,
+ clusterRadius: this._clusterConfig?.clusterRadius ?? 180,
+ clusterMaxZoom: this._clusterConfig?.clusterMaxZoom ?? 17,
+ clusterProperties: this._getClusterProperties(),
+ promoteId: "id", // Promote the id property as feature id
+ data: { type: "FeatureCollection", features: [] }, // TODO: consider preloading data to avoid tile cache misses
+ })
+ .addLayer({ ...baseLayer, id: "cluster", filter: ["has", "point_count"] })
+ .addLayer({ ...baseLayer, id: "asset", filter: ["!", ["has", "point_count"]] });
+
+ this._source = this._map.getSource("assets") as GeoJSONSource;
+
+ this._map.on("data", this._onData);
+
+ this._mapContainer.dispatchEvent(new OrMapLoadedEvent());
+ this._loaded = true;
+ }
+
+ protected _updateMarkers() {
+ if (!this._map) return;
+ const features = this._map.querySourceFeatures("assets");
+ const newAssets = this._updateAssets(features);
+ this._updateClusters(features);
+ this._mapContainer.dispatchEvent(new OrMapMarkersChangedEvent(newAssets));
+ }
+
+ private _updateAssets(features: GeoJSONFeature[]) {
+ const newAssets: Record<string, AssetWithLocation> = {};
+
+ for (const feature of features) {
+ if (!feature.properties.id) continue;
+ const id = feature.properties.id as string;
+ if (this._assets[id]) newAssets[id] = this._assets[id];
+ }
+
+ for (const id in this._assetsOnScreen) {
+ if (!newAssets[id]) delete this._assetsOnScreen[id];
+ }
+
+ this._assetsOnScreen = newAssets;
+ return Object.values(this._assetsOnScreen);
+ }
+
+ private _updateClusters(features: GeoJSONFeature[]) {
+ const newClusters: Record<string, Marker> = {};
+
+ // Create missing cluster markers
+ for (const feature of features) {
+ if (!feature.properties.cluster) continue;
+ const id: number = feature.properties.cluster_id;
+ let marker = this._cachedClusters[id] ?? this._getClusterMarker(feature);
+ // Invalidate the cached cluster marker if the type counts don't match
+ // If a new type is added, the marker will have a different cluster_id
+ if (marker._element instanceof OrClusterMarker && !marker._element.slicesMatch(feature.properties)) {
+ marker.remove();
+ marker = this._getClusterMarker(feature).addTo(this._map!);
+ }
+ newClusters[id] = marker;
+ // Add the new cluster marker if it's not already on screen
+ if (!this._clustersOnScreen[id]) marker.addTo(this._map!);
+ }
+
+ // Cleanup clusters that should no longer be on screen
+ for (const id in this._clustersOnScreen) {
+ if (!newClusters[id]) this._clustersOnScreen[id]?.remove();
+ }
+ this._clustersOnScreen = newClusters;
+ }
+
+ private _getClusterMarker(feature: GeoJSONFeature) {
+ const id: number = feature.properties.cluster_id;
+ const geometry = feature.geometry as Point;
+ const [lng, lat] = geometry.coordinates;
+
+ const slices: Slice[] = Object.entries(feature.properties)
+ .filter(([k]) => k in this._assetTypeColors)
+ .map(([type, count]) => [type, this._assetTypeColors[type], count]);
+
+ return (this._cachedClusters[id] = new Marker({
+ element: new OrClusterMarker(slices, id, lng, lat, this._map!),
+ }).setLngLat([lng, lat]));
+ }
+
+ private _hasRequired(asset: AssetWithLocation): asset is IdentifiableAsset {
+ return Boolean(asset?.id && asset?.type);
+ }
+
+ private _isMissing(asset: IdentifiableAsset, features: Feature[]) {
+ return !features?.some((f) => f.properties?.id === asset.id);
+ }
+
+ private _getClusterProperties() {
+ return Object.fromEntries(Object.keys(this._assetTypeColors).map(AssetMap._getClusterPropertyExpression));
+ }
+
+ private static _getClusterPropertyExpression(value: string) {
+ return [value, ["+", ["case", ["==", ["get", AssetMap._clusterProperty], value], 1, 0]]];
+ }
+
+ private static _assetToFeature({
+ id,
+ type,
+ name,
+ attributes,
+ }: IdentifiableAsset): Feature<Point, { id: string; name?: string; [AssetMap._clusterProperty]: string }> {
+ return {
+ type: "Feature",
+ geometry: attributes.location.value,
+ properties: { id, name, [AssetMap._clusterProperty]: type },
+ };
+ }
+}
diff --git a/ui/component/or-map/src/mapwidget.ts b/ui/component/or-map/src/base-map.ts
similarity index 81%
rename from ui/component/or-map/src/mapwidget.ts
rename to ui/component/or-map/src/base-map.ts
index eeefa14c1..ca7263d44 100644
--- a/ui/component/or-map/src/mapwidget.ts
+++ b/ui/component/or-map/src/base-map.ts
@@ -1,3 +1,4 @@
+import { GeoJsonConfig } from "@openremote/model";
import manager, { DefaultColor4 } from "@openremote/core";
import maplibregl, {
AddLayerObject,
@@ -12,43 +13,28 @@ import maplibregl, {
NavigationControl,
StyleSpecification,
GeoJSONSourceSpecification,
- MapSourceDataEvent,
} from "maplibre-gl";
-import MaplibreGeocoder from "@maplibre/maplibre-gl-geocoder";
import "@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css";
+import MaplibreGeocoder from "@maplibre/maplibre-gl-geocoder";
import debounce from "lodash.debounce";
import {
ControlPosition,
OrMapClickedEvent,
OrMapGeocoderChangeEvent,
- OrMapLoadedEvent,
OrMapLongPressEvent,
ViewSettings,
- OrMapMarkersChangedEvent,
- AssetWithLocation,
} from "./index";
import { OrMapMarker } from "./markers/or-map-marker";
-import { getLngLat, getMarkerIconAndColorFromAssetType, isWebglSupported } from "./util";
-import { Asset, GeoJsonConfig } from "@openremote/model";
-import { Feature, FeatureCollection, Geometry } from "geojson";
+import { getLngLat, isWebglSupported, metersToPixelsAtMaxZoom } from "./util";
import { isMapboxURL, transformMapboxUrl } from "./util/mapbox-url";
-import { OrClusterMarker, Slice } from "./markers/or-cluster-marker";
+import { Feature, FeatureCollection } from "geojson";
const maplibreGlStyles = require("maplibre-gl/dist/maplibre-gl.css");
const maplibreGeoCoderStyles = require("@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css");
-export interface ClusterConfig {
- cluster: boolean,
- clusterRadius: number,
- /** Until what zoom level cluster markers are shown */
- clusterMaxZoom: number
-}
-
-const metersToPixelsAtMaxZoom = (meters: number, latitude: number) => meters / 0.075 / Math.cos(latitude * Math.PI / 180);
-
let pkey: string | null;
-export class MapWidget {
+export class BaseMap {
protected _map?: MapGL;
protected _styleParent: Node;
protected _mapContainer: HTMLElement;
@@ -67,47 +53,16 @@ export class MapWidget {
protected _controls?: (IControl | [IControl, ControlPosition?])[];
protected _clickHandlers: Map<OrMapMarker, (ev: MouseEvent) => void> = new Map();
protected _geocoder?: any;
- protected _clusterConfig?: ClusterConfig;
- protected _pointsMap: any = {
- type: "FeatureCollection",
- features: []
- };
- protected _assetTypeColors: any = {};
- protected _cachedMarkers: Record<string, Marker> = {};
- protected _markersOnScreen: Record<string, Marker> = {};
- protected _assetsOnScreen: Record<string, AssetWithLocation> = {};
-
- constructor(styleParent: Node, mapContainer: HTMLElement, showGeoCodingControl = false, showBoundaryBox = false, useZoomControls = true, showGeoJson = true, clusterConfig?: ClusterConfig) {
+ constructor(styleParent: Node, mapContainer: HTMLElement, showGeoCodingControl = false, showBoundaryBox = false, useZoomControls = true, showGeoJson = true) {
this._styleParent = styleParent;
this._mapContainer = mapContainer;
this._showGeoCodingControl = showGeoCodingControl;
this._showBoundaryBox = showBoundaryBox;
this._useZoomControls = useZoomControls;
this._showGeoJson = showGeoJson;
- this._clusterConfig = clusterConfig;
}
- protected _onMove = () => this._updateMarkers();
- protected _onMoveEnd = (e: any) => {
- // Ensure marker updates happen after the frame
- requestAnimationFrame(() => {
- // On WebKit browsers the clicked marker may not be removed,
- // if the camera zoom level is directly between 2 levels
- if (e.marker instanceof OrClusterMarker) {
- this._clearMarker(e.marker._clusterId);
- }
- this._updateMarkers();
- });
- };
- protected _onData = (e: MapSourceDataEvent) => {
- if (this._map && e.isSourceLoaded && e.sourceId === "mapPoints") {
- this._map.on('move', this._onMove);
- this._map.on('moveend', this._onMoveEnd);
- this._updateMarkers();
- }
- };
-
public setCenter(center?: LngLatLike): this {
this._center = getLngLat(center);
if (this._map && this._center) {
@@ -401,10 +356,6 @@ export class MapWidget {
}
this._initLongPressEvent();
- this._map.on("load", async () => await this.load());
-
- this._mapContainer.dispatchEvent(new OrMapLoadedEvent());
- this._loaded = true;
this.createBoundaryBox()
}
@@ -416,50 +367,6 @@ export class MapWidget {
});
}
- /**
- * Load map sources, layers and events
- */
- public async load() {
- if (!this._map || !this._loaded) {
- console.warn("MapLibre Map not initialized!");
- return;
- }
-
- if (this._map.getSource('mapPoints')) {
- if (this._map.getLayer('unclustered-point')) {
- this._map.removeLayer('unclustered-point');
- }
- if (this._map.getLayer('clusters')) {
- this._map.removeLayer('clusters');
- }
- if (this._map.getLayer('cluster-count')) {
- this._map.removeLayer('cluster-count');
- }
- this._map.removeSource('mapPoints');
- }
-
- this._map.addSource('mapPoints', {
- 'type': 'geojson',
- 'cluster': this._clusterConfig?.cluster ?? true,
- 'clusterRadius': this._clusterConfig?.clusterRadius ?? 180,
- 'clusterMaxZoom': this._clusterConfig?.clusterMaxZoom ?? 17,
- 'data': this._pointsMap,
- 'clusterProperties': Object.fromEntries(Object.keys(this._assetTypeColors).map(t => [t,["+", ["case", ["==", ["get", "assetType"], t], 1, 0]]]))
- });
-
- if (!this._map.getLayer('unclustered-point')) {
- this._map.addLayer({
- id: 'unclustered-point',
- type: 'circle',
- source: 'mapPoints',
- filter: ['!', ['has', 'point_count']],
- paint: { 'circle-radius': 0 }
- });
- }
-
- this._map.on("data", this._onData);
- }
-
// Clean up of internal resources associated with the map.
// Normally used during disconnectedCallback
public unload() {
@@ -626,96 +533,6 @@ export class MapWidget {
}
}
- protected _clearMarker(id: string) {
- this._markersOnScreen[id].remove();
- delete this._assetsOnScreen[id];
- }
-
- protected _updateMarkers() {
- if (!this._map) return;
-
- const newMarkers: Record<string, Marker> = {};
- const features = this._map.querySourceFeatures('mapPoints');
-
- // Asset markers
- for (const feature of features) {
- if (!feature.properties.id) continue;
- const id: string = feature.properties.id;
- const geometry = feature.geometry as Geometry & { coordinates: LngLatLike };
- const coords = geometry.coordinates;
-
- let marker = this._cachedMarkers[id]
- if (!marker) {
- const placeholder = document.createElement("div");
- marker = this._cachedMarkers[id] = new Marker({ element: placeholder }).setLngLat(coords);
- }
- newMarkers[id] = marker;
-
- if (!this._markersOnScreen[id]) {
- marker.addTo(this._map);
- this._assetsOnScreen[id] = JSON.parse(feature.properties.asset);
- };
- }
-
- // Cluster markers
- for (const feature of features) {
- if (!feature.properties.cluster) continue;
- const id: number = feature.properties.cluster_id;
- const geometry = feature.geometry as Geometry & { coordinates: [number, number] };
- const [lng, lat] = geometry.coordinates;
-
- let marker = this._cachedMarkers[id];
- if (!marker) {
- const slices: Slice[] = Object.entries(feature.properties)
- .filter(([k]) => this._assetTypeColors.hasOwnProperty(k))
- .map(([type, count]) => [type, this._assetTypeColors[type], count]);
-
- marker = this._cachedMarkers[id] = new Marker({
- element: new OrClusterMarker(slices, id, lng, lat, this._map),
- }).setLngLat([lng, lat]);
- }
- newMarkers[id] = marker;
-
- if (!this._markersOnScreen[id]) marker.addTo(this._map);
- }
-
- for (const id in this._markersOnScreen) {
- const marker = newMarkers[id];
- if (!marker
- || marker._element instanceof OrClusterMarker && !marker._element.hasTypes(Object.keys(this._assetTypeColors))
- ) {
- this._clearMarker(id);
- }
- }
- this._markersOnScreen = newMarkers;
- this._mapContainer.dispatchEvent(new OrMapMarkersChangedEvent(Object.values(this._assetsOnScreen)));
- }
-
- public addAssetMarker(assetId: string, assetName: string, assetType: string, long: number, lat: number, asset: Asset) {
- this._assetTypeColors[assetType] = getMarkerIconAndColorFromAssetType(assetType)?.color;
- this._pointsMap.features.push({
- type: 'Feature',
- properties: {
- name: assetName,
- id: assetId,
- assetType: assetType,
- asset: asset
- },
- geometry: {
- type: "Point",
- coordinates: [ long, lat ]
- }
- });
- }
-
- public cleanUpAssetMarkers(): void {
- this._assetTypeColors = {};
- this._pointsMap = {
- type: "FeatureCollection",
- features: []
- };
- }
-
public removeMarker(marker: OrMapMarker) {
this._removeMarkerRadius(marker);
this._updateMarkerElement(marker, false);
diff --git a/ui/component/or-map/src/index.ts b/ui/component/or-map/src/index.ts
index d4c0e18e9..b13876fd1 100644
--- a/ui/component/or-map/src/index.ts
+++ b/ui/component/or-map/src/index.ts
@@ -1,8 +1,7 @@
import manager, {EventCallback} from "@openremote/core";
import {html, LitElement, PropertyValues} from "lit";
import {customElement, property, query} from "lit/decorators.js";
-import {IControl, LngLat, LngLatBoundsLike, LngLatLike, GeolocateControl} from "maplibre-gl";
-import {ClusterConfig, MapWidget} from "./mapwidget";
+import {IControl, LngLat, LngLatLike, GeolocateControl} from "maplibre-gl";
import {style} from "./style";
import "./markers/or-map-marker";
import "./markers/or-map-marker-asset";
@@ -17,43 +16,22 @@ import {OrMwcDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dial
import {getMarkerIconAndColorFromAssetType} from "./util";
import {i18next} from "@openremote/or-translate";
import debounce from "lodash.debounce";
-import { Asset, Attribute, GeoJsonConfig, GeoJSONPoint, WellknownAttributes } from "@openremote/model";
+import { AttributeEvent, GeoJsonConfig } from "@openremote/model";
import { CoordinatesControl, CoordinatesRegexPattern, getCoordinatesInputKeyHandler } from "./controls/coordinates";
+import { AssetMap } from "./asset-map";
import { CenterControl } from "./controls/center";
+import type { AssetWithLocation, ClusterConfig, ControlPosition, MapEventDetail, MapGeocoderEventDetail } from "./types";
// Re-exports
-export {Util, LngLatLike, LngLat, ClusterConfig};
+export {Util, LngLatLike, LngLat};
export * from "./markers/or-map-marker";
export * from "./markers/or-map-marker-asset";
export * from "./markers/or-cluster-marker";
export {IControl} from "maplibre-gl";
export * from "./or-map-asset-card";
export * from "./or-map-legend";
+export type * from "./types";
-export interface AssetWithLocation extends Asset {
- attributes: { [index: string]: Attribute<any> } & {
- [WellknownAttributes.LOCATION]: Attribute<GeoJSONPoint>
- };
-}
-
-export interface ViewSettings {
- center: LngLatLike;
- bounds?: LngLatBoundsLike | null;
- zoom: number;
- maxZoom: number;
- minZoom: number;
- boxZoom: boolean;
- geocodeUrl: string;
- geoJson?: GeoJsonConfig
-}
-
-export interface MapEventDetail {
- lngLat: LngLat;
- doubleClick: boolean;
-}
-export interface MapGeocoderEventDetail {
- geocode: any;
-}
export class OrMapLoadedEvent extends CustomEvent<void> {
public static readonly NAME = "or-map-loaded";
@@ -136,8 +114,6 @@ declare global {
}
}
-export type ControlPosition = "top-right" | "top-left" | "bottom-right" | "bottom-left";
-
export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (assetDescriptor, valueHolder, valueHolderDescriptor, valueDescriptor, valueChangeNotifier, options) => {
const disabled = !!(options && options.disabled);
@@ -361,7 +337,7 @@ export class OrMap extends LitElement {
public controls?: (IControl | [IControl, ControlPosition?])[];
protected _initCallback?: EventCallback;
- protected _map?: MapWidget;
+ protected _map?: AssetMap;
protected _loaded: boolean = false;
protected _resizeObserver?: ResizeObserver;
@@ -377,18 +353,24 @@ export class OrMap extends LitElement {
this.addEventListener(OrMapMarkerChangedEvent.NAME, this._onMarkerChangedEvent);
}
- public addAssetMarker(asset: AssetWithLocation) {
- const coordinates = asset?.attributes?.location.value;
- if (!coordinates?.coordinates) return;
- this._map?.addAssetMarker(asset.id ?? '', asset.name ?? '', asset.type ?? '', coordinates.coordinates[0], coordinates.coordinates[1], asset);
+ public addAsset(asset: AssetWithLocation) {
+ this._map?.addAsset(asset);
+ }
+
+ public addAssets(assets: AssetWithLocation[]) {
+ this._map?.addAssets(assets);
}
- public cleanUpAssetMarkers(): void {
- this._map?.cleanUpAssetMarkers();
+ public updateAttribute(event: AttributeEvent) {
+ this._map?.updateAttribute(event)
}
- public async reload() {
- await this._map?.load();
+ public removeAssets(ids: string[]) {
+ this._map?.removeAssets(ids);
+ }
+
+ public removeAllAssets(): void {
+ this._map?.removeAllAssets();
}
protected firstUpdated(_changedProperties: PropertyValues): void {
@@ -398,10 +380,6 @@ export class OrMap extends LitElement {
}
}
- public connectedCallback() {
- super.connectedCallback();
- }
-
public disconnectedCallback() {
super.disconnectedCallback();
if(this._resizeObserver) {
@@ -449,7 +427,7 @@ export class OrMap extends LitElement {
}
if (this._mapContainer && this._slotElement) {
- this._map = new MapWidget(this.shadowRoot!, this._mapContainer, this.showGeoCodingControl, this.showBoundaryBoxControl, this.useZoomControl, this.showGeoJson, this.cluster)
+ this._map = new AssetMap(this.shadowRoot!, this._mapContainer, this.showGeoCodingControl, this.showBoundaryBoxControl, this.useZoomControl, this.showGeoJson, this.cluster)
.setCenter(this.center)
.setZoom(this.zoom)
.setControls(this.controls)
@@ -466,8 +444,7 @@ export class OrMap extends LitElement {
}
this._slotElement!.assignedNodes({ flatten: true }).forEach((node) => {
if (node instanceof OrMapMarker) {
- const marker = node;
- this._map!.addMarker(marker)
+ this._map!.addMarker(node)
}
})
});
diff --git a/ui/component/or-map/src/markers/or-cluster-marker.ts b/ui/component/or-map/src/markers/or-cluster-marker.ts
index 291691939..f3297595c 100644
--- a/ui/component/or-map/src/markers/or-cluster-marker.ts
+++ b/ui/component/or-map/src/markers/or-cluster-marker.ts
@@ -5,9 +5,9 @@ import { GeoJSONSource, Map } from "maplibre-gl";
/**
* Slice of the donut chart for cluster markers
*/
-export type Slice = [type: string, color: string, count: number]
+export type Slice = [type: string, color: string, count: number];
-type SliceWithOffset = [...Slice, offset: number]
+type SliceWithOffset = [...Slice, offset: number];
@customElement("or-cluster-marker")
export class OrClusterMarker extends LitElement {
@@ -33,15 +33,16 @@ export class OrClusterMarker extends LitElement {
}
/**
- * Checks that all types exactly match the cluster marker types
- * @param types The types that must be present
- * @returns Whether all types are present in the cluster marker
+ * Checks that all slices match the accumulated cluster properties
+ *
+ * Note: This method assumes the slices contain the same types as `counts`. If not,
+ * a new cluster marker should be created.
+ * @param counts A record of the accumulated cluster properties to check
+ * @returns Whether the slices have the same counts as the accumulated properties
*/
- public hasTypes(types: string[]) {
- for (const type of types) {
- if (!this._slices.some(([t]) => t === type)) {
- return false;
- }
+ public slicesMatch(counts: Record<string, number>) {
+ for (const [type, , count] of this._slices) {
+ if (counts[type] !== count) return false;
}
return true;
}
@@ -70,7 +71,7 @@ export class OrClusterMarker extends LitElement {
const isClusterCountlimitSurpassed = total > this._highThreshold
return html`
- <svg
+ <svg
width="${w}"
height="${w}"
viewbox="0 0 ${w} ${w}"
@@ -102,7 +103,7 @@ export class OrClusterMarker extends LitElement {
const a1: number = 2 * Math.PI * (end - 0.25);
const x0: number = Math.cos(a0);
const y0: number = Math.sin(a0);
- const x1: number = Math.cos(a1)
+ const x1: number = Math.cos(a1);
const y1: number = Math.sin(a1);
const largeArc: 1 | 0 = end - start > 0.5 ? 1 : 0;
@@ -118,17 +119,17 @@ export class OrClusterMarker extends LitElement {
connectedCallback(): void {
super.connectedCallback();
- this.addEventListener("click", this.onClick)
+ this.addEventListener("click", this.onClick);
}
disconnectedCallback(): void {
- super.disconnectedCallback();
- this.removeEventListener("click", this.onClick)
+ super.disconnectedCallback();
+ this.removeEventListener("click", this.onClick);
}
protected async onClick() {
- if (this.lng && this.lat) {
- const zoom = await this._map.getSource<GeoJSONSource>('mapPoints')!.getClusterExpansionZoom(this._clusterId!);
+ if (this.lng != null && this.lat != null) {
+ const zoom = await this._map.getSource<GeoJSONSource>("assets")!.getClusterExpansionZoom(this._clusterId!);
// Pass `this` down as event data so the marker can be cleared programmatically
this._map.easeTo({ center: [this.lng, this.lat], zoom }, { marker: this });
}
diff --git a/ui/component/or-map/src/or-map-legend.ts b/ui/component/or-map/src/or-map-legend.ts
index bc19733fa..06b66f29b 100644
--- a/ui/component/or-map/src/or-map-legend.ts
+++ b/ui/component/or-map/src/or-map-legend.ts
@@ -34,9 +34,10 @@ export class OrMapLegend extends LitElement {
@property({ type: Array })
public assetTypes: string[] = [];
- protected _assetTypesInfo: any;
+ @property({ type: Array })
+ public excludedTypes: string[] = [];
- protected _excludedTypes: string[] = [];
+ protected _assetTypesInfo: any;
@query("#legend-content")
protected _showLegend?: HTMLDivElement;
@@ -77,7 +78,7 @@ export class OrMapLegend extends LitElement {
<div id="legend-content" hidden>
<ul>
${this.assetTypes.map(
- (assetType) => html` <li id="asset-legend" data-asset-type="${assetType}" style="display: flex;">
+ (assetType) => html`<li id="asset-legend" data-asset-type="${assetType}" style="display: flex;">
<or-icon
icon="${this._assetTypesInfo[assetType].icon}"
style="color: #${this._assetTypesInfo[assetType].color}"
@@ -85,14 +86,15 @@ export class OrMapLegend extends LitElement {
<span id="asset-label" style="flex: 1">${this._assetTypesInfo[assetType].label}</span>
<or-mwc-input
.type="${InputType.CHECKBOX}"
- .value="${!this._excludedTypes.includes(assetType)}"
+ .value="${!this.excludedTypes.includes(assetType)}"
@or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
if (ev.detail.value) {
- this._excludedTypes.splice(this._excludedTypes.indexOf(assetType), 1);
+ this.excludedTypes.splice(this.excludedTypes.indexOf(assetType), 1);
} else {
- this._excludedTypes.push(assetType);
+ this.excludedTypes.push(assetType);
}
- this.dispatchEvent(new OrMapLegendEvent(this._excludedTypes));
+ this.requestUpdate();
+ this.dispatchEvent(new OrMapLegendEvent(this.excludedTypes));
}}"
></or-mwc-input>
</li>`
diff --git a/ui/component/or-map/src/types.ts b/ui/component/or-map/src/types.ts
new file mode 100644
index 000000000..3c6e4bfd4
--- /dev/null
+++ b/ui/component/or-map/src/types.ts
@@ -0,0 +1,40 @@
+import { Asset, Attribute, GeoJsonConfig, WellknownAttributes } from "@openremote/model";
+import { LngLat, LngLatBoundsLike, LngLatLike } from "maplibre-gl";
+import { Point } from "geojson";
+
+type MandatoryAttribute<T> = Attribute<T> & { value: T };
+
+export interface AssetWithLocation extends Asset {
+ attributes: { [index: string]: Attribute<any> } & {
+ [WellknownAttributes.LOCATION]: MandatoryAttribute<Point>;
+ };
+}
+
+export interface ClusterConfig {
+ cluster: boolean;
+ clusterRadius: number;
+ /** Until what zoom level cluster markers are shown */
+ clusterMaxZoom: number;
+}
+
+export type ControlPosition = "top-right" | "top-left" | "bottom-right" | "bottom-left";
+
+export interface MapEventDetail {
+ lngLat: LngLat;
+ doubleClick: boolean;
+}
+
+export interface MapGeocoderEventDetail {
+ geocode: any;
+}
+
+export interface ViewSettings {
+ center: LngLatLike;
+ bounds?: LngLatBoundsLike | null;
+ zoom: number;
+ maxZoom: number;
+ minZoom: number;
+ boxZoom: boolean;
+ geocodeUrl: string;
+ geoJson?: GeoJsonConfig;
+}
diff --git a/ui/component/or-map/src/util/index.ts b/ui/component/or-map/src/util/index.ts
index 49888f197..84fb88009 100644
--- a/ui/component/or-map/src/util/index.ts
+++ b/ui/component/or-map/src/util/index.ts
@@ -13,6 +13,10 @@ import {AttributeMarkerColoursRange, MapMarkerColours} from "../markers/or-map-m
import { Util } from "@openremote/core";
import { AssetWithLocation } from "..";
+export function metersToPixelsAtMaxZoom(meters: number, latitude: number) {
+ return meters / 0.075 / Math.cos(latitude * Math.PI / 180);
+}
+
export function getLngLat(lngLatLike?: LngLatLike | Asset | ValueHolder<any> | GeoJSONPoint): { lng: number, lat: number } | undefined {
if (!lngLatLike) {
return;
@@ -153,7 +157,7 @@ export function isWebglSupported() {
}
export function isAssetWithLocation(asset: Asset): asset is AssetWithLocation {
- if (!asset.attributes) return false;
- const attr = asset.attributes[WellknownAttributes.LOCATION] as Attribute<GeoJSONPoint>;
- return !!attr.value && (!attr.meta || !attr.meta.hasOwnProperty(WellknownMetaItems.SHOWONDASHBOARD) || !!Util.getMetaValue(WellknownMetaItems.SHOWONDASHBOARD, attr));
+ if (!asset?.attributes) return false;
+ const attr = asset.attributes[WellknownAttributes.LOCATION] as Attribute<GeoJSONPoint> | undefined;
+ return !!attr?.value?.coordinates && (!attr.meta || !(WellknownMetaItems.SHOWONDASHBOARD in attr.meta) || !!Util.getMetaValue(WellknownMetaItems.SHOWONDASHBOARD, attr));
}