Skip to content

armgit / core

Public Imported from GitHub
0

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

Added GeoJSON functionality for Map (#1034)

Martin Peeters8ea76294ac72
diff --git a/manager/src/main/java/org/openremote/manager/map/MapService.java b/manager/src/main/java/org/openremote/manager/map/MapService.java
index 984b795f6..99e4597e3 100644
--- a/manager/src/main/java/org/openremote/manager/map/MapService.java
+++ b/manager/src/main/java/org/openremote/manager/map/MapService.java
@@ -19,12 +19,7 @@
*/
package org.openremote.manager.map;
-import com.fasterxml.jackson.annotation.JsonAutoDetect;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.undertow.server.HttpHandler;
@@ -87,16 +82,18 @@ public class MapService implements ContainerService {
LOG.log(Level.INFO, "Saving mapsettings.json..");
this.mapConfig.putNull("options");
this.mapSettings.clear();
- ObjectNode mapSettings = loadMapSettingsJson(mapSettingsPath);
+ ObjectNode mapSettingsJson = loadMapSettingsJson(mapSettingsPath);
+ if(mapSettingsJson == null) {
+ mapSettingsJson = ValueUtil.JSON.createObjectNode();
+ }
try(OutputStream out = new FileOutputStream(new File(mapSettingsPath.toUri()))){
- mapSettings.putPOJO("options", mapConfiguration);
- out.write(ValueUtil.JSON.writeValueAsString(mapSettings).getBytes());
+ mapSettingsJson.putPOJO("options", mapConfiguration);
+ out.write(ValueUtil.JSON.writeValueAsString(mapSettingsJson).getBytes());
this.setData();
- } catch (Exception exception) {
+ } catch (ClassNotFoundException | IOException | NullPointerException | SQLException exception) {
LOG.log(Level.WARNING, "Error trying to save mapsettings.json", exception);
}
-
- return mapSettings;
+ return mapSettingsJson;
}
protected static Metadata getMetadata(Connection connection) {
@@ -247,7 +244,7 @@ public class MapService implements ContainerService {
this.setData();
}
- public void setData() throws Exception{
+ public void setData() throws ClassNotFoundException, SQLException, NullPointerException {
if (mapTilesPath == null || mapSettingsPath == null) {
return;
}
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index 15a182c19..ab11d8364 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -623,6 +623,7 @@
"widgetTooSmall": "Widget is too small.",
"allowTimerangeSelect": "Allow time range selection",
"showLegend": "Show legend",
+ "showGeoJson": "Show GeoJSON overlay",
"showValueAs": "Show value as",
"deleteWidget": "Delete widget",
"myDashboards": "My dashboards",
@@ -672,6 +673,8 @@
"mapSettings": "Map settings",
"maxZoom": "Maximal zoom",
"minZoom": "Minimal zoom",
+ "geoJson": "GeoJSON",
+ "geoJsonDescription": "Customize the GeoJSON; add points, lines and polygons to be drawn on the map.",
"deleteMapCustomization": "Delete map settings",
"deleteMapCustomizationConfirm":"Are you sure you want to delete this Map customization?",
"addMapCustomization" : "Add map settings"
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index e318266c0..776f1457b 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -623,6 +623,7 @@
"widgetTooSmall": "Widget is te klein.",
"allowTimerangeSelect": "Sta tijdselectie toe",
"showLegend": "Toon legenda",
+ "showGeoJson": "Toon GeoJSON overlay",
"showValueAs": "Laat waarde zien als",
"deleteWidget": "Verwijder widget",
"myDashboards": "Mijn dashboards",
@@ -672,6 +673,8 @@
"mapSettings": "Kaartinstelling",
"maxZoom": "Maximale zoom",
"minZoom": "Minimale zoom",
+ "geoJson": "GeoJSON",
+ "geoJsonDescription": "Bewerk de GeoJSON; voeg punten, lijnen, en andere vormen toe aan de kaart.",
"deleteMapCustomization": "Kaartinstelling verwijderen",
"deleteMapCustomizationConfirm":"Weet je zeker dat je deze kaart wilt verwijderen",
"addMapCustomization" : "Voeg een Kaartinstelling toe",
diff --git a/model/src/main/java/org/openremote/model/datapoint/query/AssetDatapointIntervalQuery.java b/model/src/main/java/org/openremote/model/datapoint/query/AssetDatapointIntervalQuery.java
index b8be9d020..215412096 100644
--- a/model/src/main/java/org/openremote/model/datapoint/query/AssetDatapointIntervalQuery.java
+++ b/model/src/main/java/org/openremote/model/datapoint/query/AssetDatapointIntervalQuery.java
@@ -1,10 +1,12 @@
package org.openremote.model.datapoint.query;
import org.openremote.model.attribute.AttributeRef;
+import org.openremote.model.datapoint.DatapointInterval;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
+import java.util.Arrays;
import java.util.HashMap;
public class AssetDatapointIntervalQuery extends AssetDatapointQuery {
@@ -22,14 +24,14 @@ public class AssetDatapointIntervalQuery extends AssetDatapointQuery {
public AssetDatapointIntervalQuery(long fromTimestamp, long toTimestamp, String interval, Formula formula, boolean gapFill) {
this.fromTimestamp = fromTimestamp;
this.toTimestamp = toTimestamp;
- this.interval = interval;
+ this.interval = formatInterval(interval);
this.gapFill = gapFill;
this.formula = formula;
}
public AssetDatapointIntervalQuery(LocalDateTime fromTime, LocalDateTime toTime, String interval, Formula formula, boolean gapFill) {
this.fromTime = fromTime;
this.toTime = toTime;
- this.interval = interval;
+ this.interval = formatInterval(interval);
this.gapFill = gapFill;
this.formula = formula;
}
@@ -60,4 +62,16 @@ public class AssetDatapointIntervalQuery extends AssetDatapointQuery {
parameters.put(5, toTimestamp);
return parameters;
}
+
+ // Method that makes sure the interval is correctly formatted.
+ // The AssetDatapointIntervalQuery requires to specify an amount such as "1 day" or "5 hours",
+ // so adding an amount automatically if only a DatapointInterval such as "MINUTE" or "YEAR" is specified.
+ protected String formatInterval(String interval) {
+ boolean hasAmountSpecified = Arrays.stream(DatapointInterval.values()).noneMatch((dpInterval) -> dpInterval.toString().equalsIgnoreCase(interval));
+ if(hasAmountSpecified) {
+ return interval;
+ } else {
+ return "1 " + interval;
+ }
+ }
}
diff --git a/model/src/main/java/org/openremote/model/manager/MapRealmConfig.java b/model/src/main/java/org/openremote/model/manager/MapRealmConfig.java
index c0db44db6..b75412719 100644
--- a/model/src/main/java/org/openremote/model/manager/MapRealmConfig.java
+++ b/model/src/main/java/org/openremote/model/manager/MapRealmConfig.java
@@ -19,7 +19,7 @@
*/
package org.openremote.model.manager;
-import java.lang.reflect.Array;
+import org.openremote.model.map.GeoJsonConfig;
public class MapRealmConfig {
protected float[] center;
@@ -29,4 +29,5 @@ public class MapRealmConfig {
protected int maxZoom;
protected boolean boxZoom;
protected String geocodeUrl;
+ protected GeoJsonConfig geoJson;
}
diff --git a/model/src/main/java/org/openremote/model/map/GeoJsonConfig.java b/model/src/main/java/org/openremote/model/map/GeoJsonConfig.java
new file mode 100644
index 000000000..92ef162db
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/map/GeoJsonConfig.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2023, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.map;
+
+public class GeoJsonConfig {
+ protected Object source;
+ protected Object[] layers; // currently unused; meant for styling customization in the future
+}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
index 9cfcb5b0c..55ce74671 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
@@ -144,7 +144,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
new AssetDatapointIntervalQuery(
LocalDateTime.ofInstant(Instant.ofEpochMilli(getClockTimeOf(container)), ZoneId.systemDefault()).minus(1, ChronoUnit.HOURS),
LocalDateTime.ofInstant(Instant.ofEpochMilli(getClockTimeOf(container)), ZoneId.systemDefault()),
- "1 minute",
+ "minute",
AssetDatapointIntervalQuery.Formula.AVG,
true
)
@@ -240,7 +240,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
new AssetDatapointIntervalQuery(
LocalDateTime.ofInstant(Instant.ofEpochMilli(getClockTimeOf(container)), ZoneId.systemDefault()).minus(1, ChronoUnit.HOURS),
LocalDateTime.ofInstant(Instant.ofEpochMilli(getClockTimeOf(container)), ZoneId.systemDefault()),
- "1 minute",
+ "MINUTE",
AssetDatapointIntervalQuery.Formula.AVG,
true
)
diff --git a/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-card.ts b/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-card.ts
index 57719748a..6e5637724 100644
--- a/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-card.ts
+++ b/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-card.ts
@@ -26,6 +26,7 @@ import { DialogAction, OrMwcDialog, showDialog } from "@openremote/or-mwc-compon
import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
import { OrMapLongPressEvent } from "@openremote/or-map";
import { LngLat } from "maplibre-gl";
+import "./or-conf-map-geojson";
@customElement("or-conf-map-card")
export class OrConfMapCard extends LitElement {
@@ -201,6 +202,8 @@ export class OrConfMapCard extends LitElement {
@or-map-long-press="${(ev: OrMapLongPressEvent) => {
this.setCenter(ev.detail.lngLat);
}}" .showGeoCodingControl="${true}"
+ .showGeoJson="${this.map.geoJson != undefined}"
+ .geoJson="${this.map.geoJson}"
.useZoomControl="${false}"
style="height: 500px; width: 100%;">
${this.map.center ? html`
@@ -237,6 +240,11 @@ export class OrConfMapCard extends LitElement {
class="boundary-item"
@or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setCenter(e.detail.value)}"
.step="${.01}"></or-mwc-input>
+ <div class="subheader">${i18next.t("configuration.geoJson")}</div>
+ <span>${i18next.t("configuration.geoJsonDescription")}</span>
+ <div class="input" style="height: 56px; display: flex; align-items: center;">
+ <or-conf-map-geojson .geoJson="${this.map.geoJson}" @update="${(e: CustomEvent) => { this.map.geoJson = e.detail.value; this.requestUpdate(); }}"></or-conf-map-geojson>
+ </div>
</div>
<div class="zoom-group">
@@ -271,9 +279,11 @@ export class OrConfMapCard extends LitElement {
.step="${1}"></or-mwc-input>
</div>
- <or-mwc-input .value="${this.map.boxZoom}" .type="${InputType.SWITCH}" label="BoxZoom"
- @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.map.boxZoom = e.detail.value}"
- .step="${1}"></or-mwc-input>
+ <div class="input" style="height: 56px;">
+ <or-mwc-input .value="${this.map.boxZoom}" .type="${InputType.SWITCH}" label="BoxZoom"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.map.boxZoom = e.detail.value}"
+ .step="${1}"></or-mwc-input>
+ </div>
</div>
</div>
diff --git a/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-geojson.ts b/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-geojson.ts
new file mode 100644
index 000000000..f96242aee
--- /dev/null
+++ b/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-geojson.ts
@@ -0,0 +1,94 @@
+import { GeoJsonConfig } from "@openremote/model";
+import {DialogAction, OrMwcDialog } from "@openremote/or-mwc-components/or-mwc-dialog";
+import { i18next } from "@openremote/or-translate";
+import { html, LitElement } from "lit";
+import { customElement, property, state, query } from "lit/decorators.js";
+import "@openremote/or-components/or-ace-editor";
+import { OrAceEditorChangedEvent } from "@openremote/or-components/or-ace-editor";
+
+@customElement("or-conf-map-geojson")
+export class OrConfMapGeoJson extends LitElement {
+
+ @property()
+ protected geoJson?: GeoJsonConfig;
+
+ @state()
+ protected _jsonValid: boolean = true;
+
+ @query("#geojson-modal")
+ protected _dialog: OrMwcDialog
+
+ // Value of or-ace-editor without state to prevent UI update
+ protected _aceEditorValue: string;
+
+
+ /* --------------*/
+
+ protected render() {
+ const heading = "GeoJSON editor"
+ const content = html`
+ <or-ace-editor .value="${this.geoJson?.source}"
+ @or-ace-editor-changed="${(ev: OrAceEditorChangedEvent) => {
+ this._jsonValid = ev.detail.valid;
+ if(this._jsonValid) {
+ this._aceEditorValue = ev.detail.value;
+ }}}"
+ ></or-ace-editor>
+ `;
+ const actions: DialogAction[] = [
+ {
+ actionName: "close",
+ content: i18next.t("close")
+ },
+ {
+ actionName: "ok",
+ content: i18next.t("update"),
+ disabled: !this._jsonValid,
+ action: () => {
+ this.geoJson = this.parseGeoJson(this._aceEditorValue); // update with new value
+ this.dispatchEvent(new CustomEvent("update", { detail: { value: this.geoJson }}))
+ }
+ },
+ ]
+ const styles = html`
+ <style>
+ .mdc-dialog__surface {
+ width: 1024px;
+ overflow-x: visible !important;
+ overflow-y: visible !important;
+ }
+ #dialog-content {
+ border-top-width: 1px;
+ border-top-style: solid;
+ border-bottom-width: 1px;
+ border-bottom-style: solid;
+ padding: 0;
+ overflow: visible;
+ height: 60vh;
+ }
+ </style>
+ `
+ return html`
+ <or-mwc-input type="button" label="JSON" outlined icon="pencil" @click="${() => {this.openJsonEditor()}}"></or-mwc-input>
+ <or-mwc-dialog id="geojson-modal" .heading="${heading}" .content="${content}" .actions="${actions}" .styles="${styles}" .dismissAction="${null}"></or-mwc-dialog>
+ `
+ }
+ protected openJsonEditor() {
+ this._dialog.open();
+ }
+
+ protected parseGeoJson(jsonString: string): GeoJsonConfig {
+ let geoJsonObj;
+ try {
+ geoJsonObj = JSON.parse(jsonString);
+ } catch (err) {
+ console.warn(err);
+ this._jsonValid = false;
+ return;
+ }
+ return {
+ source: geoJsonObj,
+ layers: []
+ } as GeoJsonConfig;
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts
index 2a63cc70f..2e72a5395 100644
--- a/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts
+++ b/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts
@@ -18,7 +18,6 @@ import {style} from "../style";
import manager, {Util} from "@openremote/core";
import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
import "@openremote/or-map";
-import {OrAttributeInputChangedEvent} from "@openremote/or-attribute-input";
import {
OrMap,
MapMarkerAssetConfig,
@@ -42,6 +41,7 @@ export interface MapWidgetConfig extends OrWidgetConfig {
// Map marker related values
showLabels: boolean,
showUnits: boolean,
+ showGeoJson: boolean,
boolColors: MapMarkerColours,
textColors: [string, string][],
// Threshold related values
@@ -73,6 +73,7 @@ export class OrMapWidget implements OrWidgetEntity {
attributeRefs: [],
showLabels: false,
showUnits: false,
+ showGeoJson: true,
boolColors: {type: 'boolean', 'false': '#ef5350', 'true': '#4caf50'},
textColors: [['example', '4caf50'], ['example2', 'ef5350']],
thresholds: [[0, "#4caf50"], [75, "#ff9800"], [90, "#ef5350"]],
@@ -129,7 +130,7 @@ export class OrMapWidgetContent extends LitElement {
return html`
<div style="height: 100%; display: flex; flex-direction: column; overflow: hidden;">
<or-map id="miniMap" class="or-map" .zoom="${this.widget?.widgetConfig?.zoom}"
- .center="${this.widget?.widgetConfig?.center}"
+ .center="${this.widget?.widgetConfig?.center}" .showGeoJson="${this.widget?.widgetConfig?.showGeoJson}"
style="flex: 1;">
${(this.assets) ?
this.assets.filter((asset: Asset) => {
@@ -271,8 +272,16 @@ class OrMapWidgetSettings extends LitElement {
}
}}"
></or-mwc-input>
-
-
+ </div>
+ <div style="display: flex; justify-content: space-between; align-items: center; padding: 0 10px 12px 10px;">
+ <span>${i18next.t('dashboard.showGeoJson')}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
+ .value="${config.showGeoJson}"
+ @or-mwc-input-changed="${(event: CustomEvent) => {
+ config.showGeoJson = event.detail.value;
+ this.updateConfig(this.widget!, config, true);
+ }}"
+ ></or-mwc-input>
</div>
</div>
` : null}
diff --git a/ui/component/or-map/src/index.ts b/ui/component/or-map/src/index.ts
index 8d4789402..3edcde836 100644
--- a/ui/component/or-map/src/index.ts
+++ b/ui/component/or-map/src/index.ts
@@ -19,7 +19,7 @@ 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";
-import { MapType } from "@openremote/model";
+import {GeoJsonConfig, MapType } from "@openremote/model";
// Re-exports
export {Util, LngLatLike};
@@ -36,6 +36,7 @@ export interface ViewSettings {
minZoom: number;
boxZoom: boolean;
geocodeUrl: String;
+ geoJson?: GeoJsonConfig
}
export interface MapEventDetail {
@@ -436,6 +437,12 @@ export class OrMap extends LitElement {
@property({type: Boolean})
public useZoomControl: boolean = true;
+ @property({type: Object})
+ public geoJson?: GeoJsonConfig;
+
+ @property({type: Boolean})
+ public showGeoJson: boolean = true;
+
@property({type: Array})
public boundary: string[] = [];
@@ -483,6 +490,8 @@ export class OrMap extends LitElement {
if(this._resizeObserver) {
this._resizeObserver.disconnect();
}
+ // Clean up of internal resources associated with the map
+ this._map?.unload();
}
protected render() {
@@ -524,10 +533,11 @@ export class OrMap extends LitElement {
}
if (this._mapContainer && this._slotElement) {
- this._map = new MapWidget(this.type, this.showGeoCodingControl, this.shadowRoot!, this._mapContainer, this.showBoundaryBoxControl, this.useZoomControl)
+ this._map = new MapWidget(this.type, this.shadowRoot!, this._mapContainer, this.showGeoCodingControl, this.showBoundaryBoxControl, this.useZoomControl, this.showGeoJson)
.setCenter(this.center)
.setZoom(this.zoom)
- .setControls(this.controls);
+ .setControls(this.controls)
+ .setGeoJson(this.geoJson);
this._map.load().then(() => {
// Get markers from slot
this._observer = new FlattenedNodesObserver(this._slotElement!, (info: any) => {
diff --git a/ui/component/or-map/src/mapwidget.ts b/ui/component/or-map/src/mapwidget.ts
index 63cccdc89..a7d2de8c4 100644
--- a/ui/component/or-map/src/mapwidget.ts
+++ b/ui/component/or-map/src/mapwidget.ts
@@ -1,6 +1,8 @@
-import manager from "@openremote/core";
+import manager, { DefaultColor4 } from "@openremote/core";
import maplibregl,{
+ AnyLayer,
Control,
+ GeoJSONSource,
GeolocateControl,
IControl,
LngLat,
@@ -25,7 +27,8 @@ import {
} from "./index";
import { OrMapMarker } from "./markers/or-map-marker";
import { getLatLngBounds, getLngLat } from "./util";
-import { MapType } from "@openremote/model";
+import {GeoJsonConfig, MapType } from "@openremote/model";
+import { Feature, FeatureCollection } from "geojson";
const mapboxJsStyles = require("mapbox.js/dist/mapbox.css");
const maplibreGlStyles = require("maplibre-gl/dist/maplibre-gl.css");
@@ -45,23 +48,28 @@ export class MapWidget {
protected _loaded: boolean = false;
protected _markersJs: Map<OrMapMarker, L.Marker> = new Map();
protected _markersGl: Map<OrMapMarker, MarkerGL> = new Map();
+ protected _geoJsonConfig?: GeoJsonConfig;
+ protected _geoJsonSources: string[] = [];
+ protected _geoJsonLayers: Map<string, any> = new Map();
protected _viewSettings?: ViewSettings;
protected _center?: LngLatLike;
protected _zoom?: number;
protected _showGeoCodingControl: boolean = false;
protected _showBoundaryBox: boolean = false;
protected _useZoomControls: boolean = true;
+ protected _showGeoJson: boolean = true;
protected _controls?: (Control | IControl | [Control | IControl, ControlPosition?])[];
protected _clickHandlers: Map<OrMapMarker, (ev: MouseEvent) => void> = new Map();
protected _geocoder?: any;
- constructor(type: MapType, showGeoCodingControl: boolean, styleParent: Node, mapContainer: HTMLElement, showBoundaryBox = false, useZoomControls = true) {
+ constructor(type: MapType, styleParent: Node, mapContainer: HTMLElement, showGeoCodingControl: boolean = false, showBoundaryBox = false, useZoomControls = true, showGeoJson = true) {
this._type = type;
this._styleParent = styleParent;
this._mapContainer = mapContainer;
this._showGeoCodingControl = showGeoCodingControl;
this._showBoundaryBox = showBoundaryBox;
- this._useZoomControls= useZoomControls;
+ this._useZoomControls = useZoomControls;
+ this._showGeoJson = showGeoJson;
}
public setCenter(center?: LngLatLike): this {
@@ -178,6 +186,18 @@ export class MapWidget {
return this;
}
+ public setGeoJson(geoJsonConfig?: GeoJsonConfig): this {
+ this._geoJsonConfig = geoJsonConfig;
+ if(this._mapGl) {
+ if(this._geoJsonConfig) {
+ this.loadGeoJSON(this._geoJsonConfig);
+ } else {
+ this.loadGeoJSON(this._viewSettings?.geoJson);
+ }
+ }
+ return this;
+ }
+
public async loadViewSettings() {
let settingsResponse;
@@ -193,17 +213,24 @@ export class MapWidget {
this._viewSettings = settings.options ? settings.options[realmName] ? settings.options[realmName] : settings.options.default : null;
if (this._viewSettings) {
+
+ // If Map was already present, so only ran during updates such as realm switches
if (this._mapGl) {
this._mapGl.setMinZoom(this._viewSettings.minZoom);
this._mapGl.setMaxZoom(this._viewSettings.maxZoom);
if (this._viewSettings.bounds){
this._mapGl.setMaxBounds(this._viewSettings.bounds);
}
+ // Unload all GeoJSON that is present, and load new layers if present
+ if(this._geoJsonConfig) {
+ await this.loadGeoJSON(this._geoJsonConfig);
+ } else {
+ await this.loadGeoJSON(this._viewSettings?.geoJson);
+ }
}
if (!this._center) {
this.setCenter(this._viewSettings.center);
- }
- else {
+ } else {
this.setCenter(this._center);
}
}
@@ -412,6 +439,13 @@ export class MapWidget {
}));
}
+ // Unload all GeoJSON that is present, and load new layers if present
+ if(this._geoJsonConfig) {
+ await this.loadGeoJSON(this._geoJsonConfig);
+ } else {
+ await this.loadGeoJSON(this._viewSettings?.geoJson);
+ }
+
this._initLongPressEvent();
}
@@ -431,10 +465,171 @@ export class MapWidget {
});
}
+ // Clean up of internal resources associated with the map.
+ // Normally used during disconnectedCallback
+ public unload() {
+ if(this._mapGl) {
+ this._mapGl.remove();
+ this._mapGl = undefined;
+ }
+ if(this._mapJs) {
+ this._mapJs.remove();
+ this._mapJs = undefined;
+ }
+ }
+
protected _onMapClick(lngLat: LngLat, doubleClicked: boolean = false) {
this._mapContainer.dispatchEvent(new OrMapClickedEvent(lngLat, doubleClicked));
}
+ protected async loadGeoJSON(geoJsonConfig?: GeoJsonConfig) {
+
+ // Remove old layers
+ if(this._geoJsonLayers.size > 0) {
+ this._geoJsonLayers.forEach((layer, layerId) => this._mapGl!.removeLayer(layerId));
+ this._geoJsonLayers = new Map();
+ }
+ // Remove old sources
+ if(this._geoJsonSources.length > 0) {
+ this._geoJsonSources.forEach((sourceId) => this._mapGl!.removeSource(sourceId));
+ this._geoJsonSources = [];
+ }
+
+ // Add new ones if present
+ if (this._showGeoJson && geoJsonConfig) {
+
+ // If array of features (most of the GeoJSONs use this)
+ if(geoJsonConfig.source.type == "FeatureCollection") {
+ const groupedSources = this.groupSourcesByGeometryType(geoJsonConfig.source);
+ groupedSources?.forEach((features, type) => {
+ const newSource = {
+ type: "geojson",
+ data: {
+ type: "FeatureCollection",
+ features: features
+ }
+ } as any as GeoJSONSource;
+ const sourceInfo = this.addGeoJSONSource(newSource);
+ if(sourceInfo) {
+ this.addGeoJSONLayer(type, sourceInfo.sourceId);
+ }
+ })
+
+ // Or only 1 feature is added
+ } else if(geoJsonConfig.source.type == "Feature") {
+ const sourceInfo = this.addGeoJSONSource(geoJsonConfig.source);
+ if(sourceInfo) {
+ this.addGeoJSONLayer(sourceInfo.source.type, sourceInfo.sourceId);
+ }
+ } else {
+ console.error("Could not create layer since source type is neither 'FeatureCollection' nor 'Feature'.")
+ }
+ }
+ }
+
+ public groupSourcesByGeometryType(sources: FeatureCollection): Map<string, Feature[]> | undefined {
+ const groupedSources: Map<string, Feature[]> = new Map();
+ sources.features.forEach((feature) => {
+ let sources: Feature[] | undefined = groupedSources.get(feature.geometry.type);
+ if(sources == undefined) { sources = []; }
+ sources.push(feature);
+ groupedSources.set(feature.geometry.type, sources);
+ })
+ return groupedSources;
+ }
+
+ public addGeoJSONSource(source: GeoJSONSource): { source: GeoJSONSource, sourceId: string } | undefined {
+ if(!this._mapGl) {
+ console.error("mapGl instance not found!"); return;
+ }
+ const id = Date.now() + "-" + (this._geoJsonSources.length + 1);
+ this._mapGl.addSource(id, source)
+ this._geoJsonSources.push(id);
+ return {
+ source: source,
+ sourceId: id
+ }
+ }
+
+ public addGeoJSONLayer(typeString: string, sourceId: string) {
+ if(!this._mapGl) {
+ console.error("mapGl instance not found!"); return;
+ }
+
+ const type = typeString as "Point" | "MultiPoint" | "LineString" | "MultiLineString" | "Polygon" | "MultiPolygon" | "GeometryCollection"
+ const layerId = sourceId + "-" + type;
+
+ // If layer is not added yet
+ if( this._geoJsonLayers.get(layerId) == undefined) {
+
+ // Get realm color by getting value from CSS
+ let realmColor: string = getComputedStyle(this._mapContainer).getPropertyValue('--or-app-color4');
+ if(realmColor == undefined || realmColor.length == 0) {
+ realmColor = DefaultColor4;
+ }
+
+ let layer = {
+ id: layerId,
+ source: sourceId
+ } as any;
+
+ // Set styling based on type
+ switch (type) {
+ case "Point":
+ case "MultiPoint": {
+ layer.type = "circle";
+ layer.paint = {
+ 'circle-radius': 12,
+ 'circle-color': realmColor
+ }
+ this._geoJsonLayers.set(layerId, layer);
+ this._mapGl.addLayer(layer);
+ break;
+ }
+ case "LineString":
+ case "MultiLineString": {
+ layer.type = "line";
+ layer.paint = {
+ 'line-color': realmColor,
+ 'line-width': 4
+ };
+ this._geoJsonLayers.set(layerId, layer);
+ this._mapGl.addLayer(layer);
+ break;
+ }
+ case "Polygon":
+ case "MultiPolygon": {
+ layer.type = "fill";
+ layer.paint = {
+ 'fill-color': realmColor,
+ 'fill-opacity': 0.3
+ };
+ this._geoJsonLayers.set(layerId, layer);
+ this._mapGl.addLayer(layer);
+
+ // Add extra layer with outline
+ const outlineId = layerId + "-outline";
+ const outlineLayer = {
+ id: outlineId,
+ source: sourceId,
+ type: "line",
+ paint: {
+ 'line-color': realmColor,
+ 'line-width': 2
+ },
+ } as AnyLayer
+ this._geoJsonLayers.set(outlineId, outlineLayer);
+ this._mapGl.addLayer(outlineLayer);
+ break;
+ }
+ case "GeometryCollection": {
+ console.error("GeometryCollection GeoJSON is not implemented yet!");
+ return;
+ }
+ }
+ }
+ }
+
public addMarker(marker: OrMapMarker) {
if (marker.hasPosition()) {
this._updateMarkerElement(marker, true);
diff --git a/ui/component/or-mwc-components/src/or-mwc-dialog.ts b/ui/component/or-mwc-components/src/or-mwc-dialog.ts
index 115f168a0..cb36354a7 100644
--- a/ui/component/or-mwc-components/src/or-mwc-dialog.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-dialog.ts
@@ -305,7 +305,7 @@ export class OrMwcDialog extends LitElement {
<footer class="mdc-dialog__actions">
${this.actions ? this.actions.map((action) => {
return html`
- <div class="mdc-button mdc-dialog__button" ?data-mdc-dialog-button-default="${action.default}" data-mdc-dialog-action="${action.actionName}">
+ <div class="mdc-button mdc-dialog__button" ?data-mdc-dialog-button-default="${action.default}" data-mdc-dialog-action="${action.disabled ? undefined : action.actionName}">
${typeof(action.content) === "string" ? html`<or-mwc-input .type="${InputType.BUTTON}" @or-mwc-input-changed="${(ev: Event) => {if ((ev.currentTarget as OrMwcInput).disabled) ev.stopPropagation()}}" .disabled="${action.disabled}" .label="${action.content}"></or-mwc-input>` : action.content}
</div>`;
}) : ``}