100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Map customization and settings (#923)
Neal Geilenff83166edb82
diff --git a/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java b/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.javaindex 1d2c93ba2..63150afd4 100644--- a/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/map/MapResourceImpl.java@@ -23,10 +23,13 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import org.openremote.container.web.WebResource;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.model.http.RequestParams;+import org.openremote.model.manager.MapRealmConfig;import org.openremote.model.map.MapResource;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.Response;+import java.io.IOException;+import java.util.Map;public class MapResourceImpl extends WebResource implements MapResource {@@ -38,6 +41,11 @@ public class MapResourceImpl extends WebResource implements MapResource {this.identityService = identityService;}+ @Override+ public Object saveSettings(RequestParams requestParams, Map<String, MapRealmConfig> mapConfig) throws Exception {+ return mapService.saveMapConfig(mapConfig);+ }+@Overridepublic ObjectNode getSettings(RequestParams requestParams) {return mapService.getMapSettings(diff --git a/manager/src/main/java/org/openremote/manager/map/MapService.java b/manager/src/main/java/org/openremote/manager/map/MapService.javaindex 49a22579a..f78e0b3ca 100644--- a/manager/src/main/java/org/openremote/manager/map/MapService.java+++ b/manager/src/main/java/org/openremote/manager/map/MapService.java@@ -19,7 +19,12 @@*/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;@@ -30,10 +35,15 @@ import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebService;import org.openremote.model.Container;import org.openremote.model.ContainerService;+import org.openremote.model.manager.MapRealmConfig;import org.openremote.model.util.TextUtil;import org.openremote.model.util.ValueUtil;import javax.ws.rs.core.UriBuilder;+import java.io.File;+import java.io.FileOutputStream;+import java.io.IOException;+import java.io.OutputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;@@ -44,6 +54,8 @@ import java.sql.ResultSet;import java.util.HashMap;import java.util.Map;import java.util.Optional;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.ConcurrentMap;import java.util.logging.Level;import java.util.logging.Logger;@@ -75,8 +87,32 @@ public class MapService implements ContainerService {protected Metadata metadata;protected ObjectNode mapConfig;protected ObjectNode mapSource;- protected Map<String, ObjectNode> mapSettings = new HashMap<>();- protected Map<String, ObjectNode> mapSettingsJs = new HashMap<>();+ protected ConcurrentMap<String, ObjectNode> mapSettings = new ConcurrentHashMap<>();+ protected ConcurrentMap<String, ObjectNode> mapSettingsJs = new ConcurrentHashMap<>();++ public ObjectNode saveMapConfig(Map<String, MapRealmConfig> mapConfiguration) throws Exception {+ LOG.log(Level.INFO, "Saving mapsettings.json");+ this.mapConfig.putNull("options");+ this.mapSettings.clear();+ ObjectNode mapSettings = loadMapSettingsJson(mapSettingsPath);+ try(OutputStream out = new FileOutputStream(new File(mapSettingsPath.toUri()))){+ ObjectMapper mapper = new ObjectMapper();+ mapSettings.putPOJO("options", mapConfiguration);+ mapper+ .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)+ .setSerializationInclusion(JsonInclude.Include.NON_NULL)+ .enable(SerializationFeature.INDENT_OUTPUT);++ out.write(mapper.writeValueAsString(mapSettings).getBytes());+ out.close();+ this.setData();+ } catch (IOException exception) {+ LOG.log(Level.WARNING, "Saving mapsettings.json error", exception);+ throw exception;+ }++ return mapSettings;+ }protected static Metadata getMetadata(Connection connection) {@@ -223,7 +259,10 @@ public class MapService implements ContainerService {@Overridepublic void start(Container container) throws Exception {+ this.setData();+ }+ public void setData() throws Exception{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.jsonindex 99dfec88f..81b867e5c 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -600,6 +600,11 @@"zoom": "Zoom","center": "Center"},+ "south": "South",+ "east": "East",+ "west": "West",+ "north": "North",+ "default": "Default","appearance": "Appearance","configuration": {"" : "Appearance",@@ -610,6 +615,8 @@"defaultLanguage": "Default language","images": "Images","logo": "Logo",+ "center": "Center",+ "centerDescription": "The center point where the user will start on when loading the map","logoMobile": "Logo mobile","realmColors": "Realm colours","--or-app-color4": "Primary: buttons, actions, and list headers",@@ -625,7 +632,17 @@"secondaryNavigation" : "Secondary menu","reloadPage" : "To see the changes that have been made, reload the page","deleteRealmCustomization": "Delete Style",- "deleteRealmCustomizationConfirm":"Are you sure you want to delete this Realm style?"+ "deleteRealmCustomizationConfirm":"Are you sure you want to delete this Realm style?",+ "mapBounds": "Boundaries",+ "mapBoundsDescription": "Define a view box that the user sees",+ "mapZoom": "Zoom",+ "mapZoomDescription": "Define the zoom level. The entire Earth is '1' and '24' shows the most detail",+ "mapSettings": "Map settings",+ "maxZoom": "Maximal zoom",+ "minZoom": "Minimal zoom",+ "deleteMapCustomization": "Delete map settings",+ "deleteMapCustomizationConfirm":"Are you sure you want to delete this Map customization?",+ "addMapCustomization" : "Add map settings"},"mqttSessions": "MQTT sessions","address": "Address",diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex 3f2f1e39e..3dfd9298f 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -600,6 +600,11 @@"zoom": "Zoom","center": "Middelpunt"},+ "south": "Zuid",+ "east": "Oost",+ "west": "West",+ "north": "Noord",+ "default": "Standaard","appearance": "Weergave","configuration": {"" : "Weergave",@@ -610,6 +615,8 @@"defaultLanguage": "Standaard taal","images": "Afbeeldingen","logo": "Logo",+ "center": "Midden",+ "centerDescription": "Het midden waar de gebruiker zal starten wanneer de kaart wordt geladen.","logoMobile": "Logo mobiel","realmColors": "Realm kleuren","--or-app-color4": "Primair: knoppen, acties, and lijst header",@@ -625,6 +632,16 @@"secondaryNavigation" : "Secundair menu","reloadPage" : "Om de wijzigingen te zien die gemaakt zijn, herlaad de pagina","deleteRealmCustomization": "Verwijder stijl",- "deleteRealmCustomizationConfirm":"Weet je zeker dat je deze realm stijl wilt verwijderen?"+ "deleteRealmCustomizationConfirm":"Weet je zeker dat je deze realm stijl wilt verwijderen?",+ "mapBounds": "Randen",+ "mapBoundsDescription": "Defineer het gebied dat de gebruiker kan gebruiken",+ "mapZoom": "Zoom",+ "mapZoomDescription": "Defineer het zoom niveau. De gehele wereld is '1' en '24' laat het meeste detail zien",+ "mapSettings": "Kaartinstelling",+ "maxZoom": "Maximale zoom",+ "minZoom": "Minimale zoom",+ "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/manager/MapConfig.java b/model/src/main/java/org/openremote/model/manager/MapConfig.javanew file mode 100644index 000000000..0ac7dabbb--- /dev/null+++ b/model/src/main/java/org/openremote/model/manager/MapConfig.java@@ -0,0 +1,26 @@+/*+ * Copyright 2022, 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.manager;++import java.util.Map;++public class MapConfig {+ protected Map<String, MapRealmConfig> options;+}diff --git a/model/src/main/java/org/openremote/model/manager/MapRealmConfig.java b/model/src/main/java/org/openremote/model/manager/MapRealmConfig.javanew file mode 100644index 000000000..c0db44db6--- /dev/null+++ b/model/src/main/java/org/openremote/model/manager/MapRealmConfig.java@@ -0,0 +1,32 @@+/*+ * Copyright 2022, 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.manager;++import java.lang.reflect.Array;++public class MapRealmConfig {+ protected float[] center;+ protected float[] bounds;+ protected int zoom;+ protected int minZoom;+ protected int maxZoom;+ protected boolean boxZoom;+ protected String geocodeUrl;+}diff --git a/model/src/main/java/org/openremote/model/map/MapResource.java b/model/src/main/java/org/openremote/model/map/MapResource.javaindex 50020e006..b6ba815d1 100644--- a/model/src/main/java/org/openremote/model/map/MapResource.java+++ b/model/src/main/java/org/openremote/model/map/MapResource.java@@ -22,14 +22,24 @@ package org.openremote.model.map;import com.fasterxml.jackson.databind.node.ObjectNode;import io.swagger.v3.oas.annotations.tags.Tag;import org.openremote.model.http.RequestParams;+import org.openremote.model.manager.MapRealmConfig;import javax.ws.rs.*;import javax.ws.rs.core.MediaType;+import java.io.IOException;+import java.util.Map;@Tag(name = "Map")@Path("map")public interface MapResource {+ /**+ * Saves the settings for maps+ */+ @PUT+ @Produces(MediaType.APPLICATION_JSON)+ Object saveSettings(@BeanParam RequestParams requestParams, Map<String, MapRealmConfig> mapConfig) throws Exception;+/*** Returns style used to initialise Mapbox GL* @returndiff --git a/ui/app/manager/src/components/configuration/or-conf-map/index.ts b/ui/app/manager/src/components/configuration/or-conf-map/index.tsnew file mode 100644index 000000000..eae69bbf3--- /dev/null+++ b/ui/app/manager/src/components/configuration/or-conf-map/index.ts@@ -0,0 +1,138 @@+import { css, html, LitElement, PropertyValues } from "lit";+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";+import "./or-conf-map-card";+import { customElement, property } from "lit/decorators.js";+import manager from "@openremote/core";+import { MapConfig } from "@openremote/model";+import { DialogAction, OrMwcDialog, showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";+import { i18next } from "@openremote/or-translate";+import "@openremote/or-components/or-loading-indicator";+++@customElement("or-conf-map")+export class OrConfMap extends LitElement {+++ static styles = css`+ #btn-add-realm {+ margin-top: 4px;+ }+ `;++ @property({attribute: false})+ public config: MapConfig = {};++ protected _availableRealms: {name:string, displayName:string}[] = [];+ protected _allRealms: {name:string, displayName:string}[] = [];+ protected _addedRealm: null|string = null++ protected firstUpdated(_changedProperties: Map<PropertyKey, unknown>): void {+ const app = this+ manager.rest.api.RealmResource.getAccessible().then((response)=>{+ app._allRealms = response.data as {name:string, displayName:string}[];+ app._allRealms.push({name: 'default', displayName: 'Default'})+ app._loadListOfAvailableRealms()+ });+ }++ protected _removeRealm(realm:string){+ if (this.config){+ delete this.config[realm]+ this._loadListOfAvailableRealms()+ this.requestUpdate()+ }+ }++ protected _loadListOfAvailableRealms(){+ const app = this+ this._availableRealms = this._allRealms.filter(function(realm){+ if (!!realm.name && !!app.config){+ if (realm.name in app.config){+ return null+ }+ }+ return realm+ }).sort(function(a, b){+ if (a.displayName && b.displayName){+ return (a.displayName > b.displayName) ? 1 : -1+ }+ return -1+ })+ }++ protected _showAddingRealmDialog(){+ this._addedRealm = null;+ const _AddRealmToView = () => {+ if (this._addedRealm){+ if (!this.config){+ this.config = {}+ }+ this.config[this._addedRealm] = {bounds: [4.42, 51.88, 4.55, 51.94], center: [4.485222, 51.911712], zoom: 14, minZoom: 14, maxZoom: 19, boxZoom: false}+ this._loadListOfAvailableRealms()+ this.requestUpdate()+ return true+ }+ return false+ }+ const dialogActions: DialogAction[] = [+ {+ actionName: "cancel",+ content: i18next.t("cancel")+ },+ {+ default: true,+ actionName: "ok",+ content: i18next.t("ok"),+ action: _AddRealmToView+ },++ ];+ const dialog = showDialog(new OrMwcDialog()+ .setHeading(i18next.t('configuration.addMapCustomization'))+ .setActions(dialogActions)+ .setContent(html `+ <or-mwc-input class="selector" label="Realm" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._addedRealm = e.detail.value}" .type="${InputType.SELECT}" .options="${Object.entries(this._availableRealms).map(([key, value]) => {return [value.name, value.displayName]})}"></or-mwc-input>+ `)+ .setStyles(html`+ <style>+ .mdc-dialog__surface {+ padding: 4px 8px;+ }+ #dialog-content {+ flex: 1;+ overflow: visible;+ min-height: 0;+ padding: 0;+ }+ or-mwc-input.selector {+ width: 300px;+ display: block;+ padding: 10px 20px;+ }+ </style>+ `)+ .setDismissAction(null));++ }++++ updated(changedProperties: PropertyValues) {+ super.updated(changedProperties);+ }++ render() {+ const app = this;+ return html`+ <div class="panels">+ ${Object.entries(this.config === undefined ? {} : this.config).map(([key , value]) => {+ return html`<or-conf-map-card .expanded="${app._addedRealm === key}" .name="${key}" .map="${value}" .onRemove="${() => {app._removeRealm(key)}}"></or-conf-map-card>`+ })}+ </div>++ <or-mwc-input id="btn-add-realm" .type="${InputType.BUTTON}" .label="${i18next.t('configuration.addMapCustomization')}" icon="plus" @click="${() => this._showAddingRealmDialog()}"></or-mwc-input>+ `+ }+++}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.tsnew file mode 100644index 000000000..57719748a--- /dev/null+++ b/ui/app/manager/src/components/configuration/or-conf-map/or-conf-map-card.ts@@ -0,0 +1,290 @@+/*+ * Copyright 2022, 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/>.+ */+import { css, html, LitElement } from "lit";+import { customElement, property } from "lit/decorators.js";+import "@openremote/or-components/or-file-uploader";+import { i18next } from "@openremote/or-translate";+import { MapRealmConfig } from "@openremote/model";+import { DialogAction, OrMwcDialog, showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";+import { OrMapLongPressEvent } from "@openremote/or-map";+import { LngLat } from "maplibre-gl";++@customElement("or-conf-map-card")+export class OrConfMapCard extends LitElement {++ static styles = css`+ #remove-map {+ margin: 12px 0 0 0;+ }++ .subheader {+ padding: 10px 0 4px;+ font-weight: bolder;+ }++ .d-inline-flex {+ display: inline-flex;+ }++ .panel-content {+ padding: 0 24px 24px;+ }++ .description {+ font-size: 12px;+ }++ or-collapsible-panel {+ margin-bottom: 10px;+ }++ .boundary-container {+ width: 50%;+ }++ .boundary-item, .input {+ width: 100%;+ max-width: 800px;+ padding: 10px 0;+ }++ .input or-mwc-input:not([icon]) {+ width: 80%;+ }++ .zoom-group {+ width: 50%;+ padding-left: 12px;+ }++ .map-container {+ width: 100%+ }+ .settings-container{+ display: inline-flex;+ }++ @media screen and (max-width: 768px) {+ .zoom-group, .boundary-container{+ width: 100%;+ padding: unset;+ }+ .settings-container{+ display: block;+ }+ }+ `;++ @property({ attribute: false })+ public map: MapRealmConfig = {};++ @property({ attribute: true })+ public name: string = "";++ @property({ type: Boolean })+ expanded: boolean = false;++ @property({ attribute: true })+ public onRemove: CallableFunction = () => {+ };++ protected _showRemoveMapDialog() {++ const dialogActions: DialogAction[] = [+ {+ actionName: "cancel",+ content: i18next.t("cancel"),+ },+ {+ default: true,+ actionName: "ok",+ content: i18next.t("yes"),+ action: () => {+ this.onRemove();+ },+ },++ ];+ const dialog = showDialog(new OrMwcDialog()+ .setHeading(i18next.t("delete"))+ .setActions(dialogActions)+ .setContent(html`+ ${i18next.t("configuration.deleteMapCustomizationConfirm")}+ `)+ .setStyles(html`+ <style>+ .mdc-dialog__surface {+ padding: 4px 8px;+ }++ #dialog-content {+ padding: 24px;+ }+ </style>+ `)+ .setDismissAction(null));++ }++ protected firstUpdated(_changedProperties: Map<PropertyKey, unknown>): void {+ }++ protected setBoundary(key: number, value: any) {+ this.map.bounds[key] = parseFloat(parseFloat(value).toFixed(2));+ this.map.bounds = JSON.parse(JSON.stringify(this.map.bounds));+ this.requestUpdate();+ }++ protected setCenter(cor: LngLat|string) {+ let centerCoordinate: LngLat+ if (typeof cor == "string"){+ // @ts-ignore+ centerCoordinate = {+ lat: parseFloat(cor.split(',')[1]),+ lng: parseFloat(cor.split(',')[0])+ }+ } else {+ centerCoordinate = cor+ }+ const BetweenNorthSouth = this.map.bounds[3] > centerCoordinate.lat && this.map.bounds[1] < centerCoordinate.lat;+ const BetweenWestEast = this.map.bounds[0] < centerCoordinate.lng && this.map.bounds[2] > centerCoordinate.lng;+ if (!(BetweenNorthSouth && BetweenWestEast)) {+ this.map.bounds = [+ parseFloat((centerCoordinate.lng - .2).toFixed(3)),+ parseFloat((centerCoordinate.lat - .1).toFixed(3)),+ parseFloat((centerCoordinate.lng + .2).toFixed(3)),+ parseFloat((centerCoordinate.lat + .1).toFixed(3)),+ ];+ }+ this.map.center = [centerCoordinate.lng, centerCoordinate.lat];+ this.requestUpdate();+ }++ protected setZoom(nr:number){+ this.zoom = nr;+ return this.requestUpdate()+ }++ protected zoom = 1;+++ render() {+ return html`+ <or-collapsible-panel+ .expanded="${this.expanded}">+ <div slot="header" class="header-container">+ ${this.name}+ </div>+ <div slot="content" class="panel-content">+ <div class="map-container">+ <div class="subheader">${i18next.t("map")}</div>+ <or-map id="vectorMap" .showBoundaryBoxControl="${true}" .zoom="${this.zoom}"+ .boundary="${this.map.bounds}"+ @or-map-long-press="${(ev: OrMapLongPressEvent) => {+ this.setCenter(ev.detail.lngLat);+ }}" .showGeoCodingControl="${true}"+ .useZoomControl="${false}"+ style="height: 500px; width: 100%;">+ ${this.map.center ? html`+ <or-map-marker id="geo-json-point-marker" .lng="${this.map.center[0]}"+ .lat="${this.map.center[1]}"></or-map-marker>` : ""}++ </or-map>+ </div>++ <div class="settings-container">+ <div class="boundary-container">+ <div class="subheader">${i18next.t("configuration.mapBounds")}</div>+ <span>${i18next.t("configuration.mapBoundsDescription")}</span>+ <or-mwc-input .value="${this.map?.bounds[3]}" .type="${InputType.NUMBER}" .label="${i18next.t("north")}"+ class="boundary-item"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setBoundary(3, e.detail.value)}"+ .step="${.01}"></or-mwc-input>+ <or-mwc-input .value="${this.map?.bounds[2]}" .type="${InputType.NUMBER}" .label="${i18next.t("east")}"+ class="boundary-item"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setBoundary(2, e.detail.value)}"+ .step="${.01}"></or-mwc-input>+ <or-mwc-input .value="${this.map?.bounds[0]}" .type="${InputType.NUMBER}" .label="${i18next.t("west")}"+ class="boundary-item"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setBoundary(0, e.detail.value)}"+ .step="${.01}"></or-mwc-input>+ <or-mwc-input .value="${this.map?.bounds[1]}" .type="${InputType.NUMBER}" .label="${i18next.t("south")}"+ class="boundary-item"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setBoundary(1, e.detail.value)}"+ .step="${.01}"></or-mwc-input>+ <div class="subheader">${i18next.t("configuration.center")}</div>+ <span>${i18next.t("configuration.centerDescription")}</span>+ <or-mwc-input .value="${Array.isArray(this.map.center) ? this.map.center.join() : undefined}"+ .type="${InputType.TEXT}" label="${i18next.t("configuration.center")}"+ class="boundary-item"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setCenter(e.detail.value)}"+ .step="${.01}"></or-mwc-input>+ </div>++ <div class="zoom-group">+ <div class="subheader">${i18next.t("configuration.mapZoom")}</div>+ <span>${i18next.t("configuration.mapZoomDescription")}</span>+ <div class="input">+ <or-mwc-input .value="${this.map.zoom}" .type="${InputType.NUMBER}" .label="${i18next.t('default')}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.map.zoom = e.detail.value}"+ .step="${1}"></or-mwc-input>+ <or-mwc-input .type="${InputType.BUTTON}" icon="eye"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setZoom(this.map.zoom)}"+ .step="${1}"></or-mwc-input>+ </div>+ <div class="input">+ <or-mwc-input .value="${this.map.minZoom}" .type="${InputType.NUMBER}"+ .label="${i18next.t("configuration.minZoom")}"+ max="${this.map.maxZoom}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => {this.map.minZoom = e.detail.value; this.requestUpdate() }}"+ .step="${1}"></or-mwc-input>+ <or-mwc-input .type="${InputType.BUTTON}" icon="eye"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setZoom(this.map.minZoom)}"+ .step="${1}"></or-mwc-input>+ </div>+ <div class="input">+ <or-mwc-input .value="${this.map.maxZoom}" .type="${InputType.NUMBER}"+ .label="${i18next.t("configuration.maxZoom")}"+ min="${this.map.minZoom}"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => { this.map.maxZoom = e.detail.value;this.requestUpdate()}}"+ .step="${1}"></or-mwc-input>+ <or-mwc-input .type="${InputType.BUTTON}" icon="eye"+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setZoom(this.map.maxZoom)}"+ .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>+ </div>+++ <or-mwc-input outlined .type="${InputType.BUTTON}" id="remove-map"+ .label="${i18next.t("configuration.deleteMapCustomization")}"+ @click="${() => {+ this._showRemoveMapDialog();+ }}"></or-mwc-input>+ </div>+ </or-collapsible-panel>+ `;+ }+}diff --git a/ui/app/manager/src/components/configuration/or-conf-realm/index.ts b/ui/app/manager/src/components/configuration/or-conf-realm/index.tsindex bfd9210f0..62c5da733 100644--- a/ui/app/manager/src/components/configuration/or-conf-realm/index.ts+++ b/ui/app/manager/src/components/configuration/or-conf-realm/index.ts@@ -60,21 +60,21 @@ export class OrConfRealm extends LitElement {}}- protected _loadListOfAvailableRealms(){- const app = this- this._availableRealms = this._allRealms.filter(function(realm){- if (realm.name && app.config?.realms){- if (!app.config?.realms[realm.name]){- return realm+ protected _loadListOfAvailableRealms() {+ const app = this;+ this._availableRealms = this._allRealms.filter(function(realm) {+ if (!!realm.name && !!app.config){+ if (realm.name in app.config?.realms){+ return null}}- return null- }).sort(function(a, b){- if (a.displayName && b.displayName){- return (a.displayName > b.displayName) ? 1 : -1+ return realm;+ }).sort(function(a, b) {+ if (a.displayName && b.displayName) {+ return (a.displayName > b.displayName) ? 1 : -1;}- return -1- })+ return -1;+ });}protected _showAddingRealmDialog(){diff --git a/ui/app/manager/src/pages/page-configuration.ts b/ui/app/manager/src/pages/page-configuration.tsindex 9aacae748..5ec76c0d0 100644--- a/ui/app/manager/src/pages/page-configuration.ts+++ b/ui/app/manager/src/pages/page-configuration.ts@@ -28,6 +28,7 @@ import "@openremote/or-components/or-collapsible-panel";import "@openremote/or-mwc-components/or-mwc-input";import "../components/configuration/or-conf-json";import "../components/configuration/or-conf-realm/index";+import "../components/configuration/or-conf-map/index";import { ManagerAppConfig } from "@openremote/model";import { i18next } from "@openremote/or-translate";import "@openremote/or-components/or-loading-indicator";@@ -142,7 +143,7 @@ export class PageConfiguration extends Page<AppStateKeyed> {}get name(): string {- return "configuration";+ return "appearance";}constructor(store: Store<AppStateKeyed>) {@@ -150,19 +151,29 @@ export class PageConfiguration extends Page<AppStateKeyed> {}private urlPrefix:string = (CONFIG_URL_PREFIX || "")- private getManagerConfig(): Promise<boolean> {- return fetch(this.urlPrefix + "/manager_config.json", { cache: "reload" })+ private mapConfig = {};+ private getManagerConfig(): void {+ fetch(this.urlPrefix + "/manager_config.json", { cache: "reload" }).then(async (response) => {return response.json().then((json) => {this.managerConfiguration = json;this.loading = false;- this.requestUpdate();return true;});}).catch(() => {- return false;- });+ this.managerConfiguration = {};+ this.loading = false;+ return false;+ }).finally(() => {+ this.requestUpdate();+ });++ manager.rest.api.MapResource.getSettings().then((response) => {+ this.mapConfig = response.data.options+ this.loading = false;+ this.requestUpdate();+ })}private loading: boolean = true;@@ -186,6 +197,9 @@ export class PageConfiguration extends Page<AppStateKeyed> {});app.requestUpdate();})+ manager.rest.api.MapResource.saveSettings(this.mapConfig).then(() => {+ app.requestUpdate();+ })})this.getManagerConfig();@@ -200,24 +214,28 @@ export class PageConfiguration extends Page<AppStateKeyed> {return html`${this.loading ? html`<or-loading-indicator .overlay="${true}"></or-loading-indicator>` : html`- <div id="wrapper">- <div id="header-wrapper">- <div id="header-title">- <or-icon icon="palette-outline"></or-icon>- ${i18next.t("appearance")}- </div>- <div id="header-actions">- <or-conf-json .managerConfig="${this.managerConfiguration}" class="hide-mobile"></or-conf-json>- <or-mwc-input id="save-btn" raised="" type="button" .label="${i18next.t("save")}"- @click="${() => {- document.dispatchEvent(new CustomEvent("saveManagerConfig", { detail: { value: this.managerConfiguration } }));- }}"></or-mwc-input>- </div>- </div>- <or-panel .heading="${i18next.t("configuration.realmStyling")}">- <or-conf-realm .config="${this.managerConfiguration}"></or-conf-realm>- </or-panel>- </div>`}+ <div id="wrapper">+ <div id="header-wrapper">+ <div id="header-title">+ <or-icon icon="palette-outline"></or-icon>+ ${i18next.t("appearance")}+ </div>+ <div id="header-actions">+ <or-conf-json .managerConfig="${this.managerConfiguration}"+ class="hide-mobile"></or-conf-json>+ <or-mwc-input id="save-btn" raised="" type="button" .label="${i18next.t("save")}"+ @click="${() => {+ document.dispatchEvent(new CustomEvent("saveManagerConfig", { detail: { value: this.managerConfiguration } }));+ }}"></or-mwc-input>+ </div>+ </div>+ <or-panel .heading="${i18next.t("configuration.realmStyling")}">+ <or-conf-realm .config="${this.managerConfiguration}"></or-conf-realm>+ </or-panel>+ <or-panel .heading="${i18next.t("configuration.mapSettings").toUpperCase()}">+ <or-conf-map .config="${this.mapConfig}"></or-conf-map>+ </or-panel>+ </div>`}`;diff --git a/ui/app/manager/src/pages/page-map.ts b/ui/app/manager/src/pages/page-map.tsindex b11d2be5a..719ff280c 100644--- a/ui/app/manager/src/pages/page-map.ts+++ b/ui/app/manager/src/pages/page-map.ts@@ -187,8 +187,8 @@ export class PageMap extends Page<MapStateKeyed> {if (this.config && this.config.markers) {markerLabelAttributes = Object.values(this.config.markers)- .filter(assetTypeMarkerConfig => assetTypeMarkerConfig.attributeName)- .map(assetTypeMarkerConfig => assetTypeMarkerConfig.attributeName);+ .filter(assetTypeMarkerConfig => assetTypeMarkerConfig.attributeName)+ .map(assetTypeMarkerConfig => assetTypeMarkerConfig.attributeName);}return [@@ -293,38 +293,38 @@ export class PageMap extends Page<MapStateKeyed> {};protected getRealmState = createSelector(- [this._realmSelector],- async (realm) => {- if (this._assets.length > 0) {- // Clear existing assets- this._assets = [];- }- this.unsubscribeAssets();- this.subscribeAssets(realm);-- if (this._map) {- this._map.refresh();- }- }+ [this._realmSelector],+ async (realm) => {+ if (this._assets.length > 0) {+ // Clear existing assets+ this._assets = [];+ }+ this.unsubscribeAssets();+ this.subscribeAssets(realm);++ if (this._map) {+ this._map.refresh();+ }+ })protected _getMapAssets = createSelector(- [this._assetSelector],- (assets) => {- return assets;- });+ [this._assetSelector],+ (assets) => {+ return assets;+ });protected _getCurrentAsset = createSelector(- [this._assetSelector, this._paramsSelector],- (assets, params) => {- const currentId = params ? params.id : undefined;+ [this._assetSelector, this._paramsSelector],+ (assets, params) => {+ const currentId = params ? params.id : undefined;- if (!currentId) {- return null;- }+ if (!currentId) {+ return null;+ }- return assets.find((asset) => asset.id === currentId);- });+ return assets.find((asset) => asset.id === currentId);+ });protected _setCenter(geocode: any) {this._map!.center = [geocode.geometry.coordinates[0], geocode.geometry.coordinates[1]];@@ -347,26 +347,26 @@ export class PageMap extends Page<MapStateKeyed> {<or-map id="map" class="or-map" showGeoCodingControl @or-map-geocoder-change="${(ev: OrMapGeocoderChangeEvent) => {this._setCenter(ev.detail.geocode);}}">${- this._assets.filter((asset) => {- if (!asset.attributes) {- return false;- }- const attr = asset.attributes[WellknownAttributes.LOCATION] as Attribute<GeoJSONPoint>;- return !attr.meta || !attr.meta.hasOwnProperty(WellknownMetaItems.SHOWONDASHBOARD) || !!Util.getMetaValue(WellknownMetaItems.SHOWONDASHBOARD, attr);- })- .sort((a,b) => {- if (a.attributes[WellknownAttributes.LOCATION].value && b.attributes[WellknownAttributes.LOCATION].value){- return b.attributes[WellknownAttributes.LOCATION].value.coordinates[1] - a.attributes[WellknownAttributes.LOCATION].value.coordinates[1];- } else {- return;- }- })- .map(asset => {- return html`+ this._assets.filter((asset) => {+ if (!asset.attributes) {+ return false;+ }+ const attr = asset.attributes[WellknownAttributes.LOCATION] as Attribute<GeoJSONPoint>;+ return !attr.meta || !attr.meta.hasOwnProperty(WellknownMetaItems.SHOWONDASHBOARD) || !!Util.getMetaValue(WellknownMetaItems.SHOWONDASHBOARD, attr);+ })+ .sort((a,b) => {+ if (a.attributes[WellknownAttributes.LOCATION].value && b.attributes[WellknownAttributes.LOCATION].value){+ return b.attributes[WellknownAttributes.LOCATION].value.coordinates[1] - a.attributes[WellknownAttributes.LOCATION].value.coordinates[1];+ } else {+ return;+ }+ })+ .map(asset => {+ return html`<or-map-marker-asset ?active="${this._currentAsset && this._currentAsset.id === asset.id}" .asset="${asset}" .config="${this.config.markers}"></or-map-marker-asset>`;- })- }+ })+ }</or-map>`;}diff --git a/ui/component/or-map/src/index.ts b/ui/component/or-map/src/index.tsindex f8cee3dde..8d4789402 100644--- a/ui/component/or-map/src/index.ts+++ b/ui/component/or-map/src/index.ts@@ -30,7 +30,7 @@ export * from "./or-map-asset-card";export interface ViewSettings {center: LngLatLike;- bounds: LngLatBoundsLike;+ bounds?: LngLatBoundsLike | null;zoom: number;maxZoom: number;minZoom: number;@@ -430,6 +430,15 @@ export class OrMap extends LitElement {@property({type: Boolean})public showGeoCodingControl: boolean = false;+ @property({type: Boolean})+ public showBoundaryBoxControl: boolean = false;++ @property({type: Boolean})+ public useZoomControl: boolean = true;++ @property({type: Array})+ public boundary: string[] = [];+public controls?: (Control | IControl | [Control | IControl, ControlPosition?])[];protected _initCallback?: EventCallback;@@ -493,6 +502,9 @@ export class OrMap extends LitElement {if (changedProperties.has("center") || changedProperties.has("zoom")) {this.flyTo(this.center, this.zoom);}+ if (changedProperties.has("boundary") && this.showBoundaryBoxControl){+ this._map?.createBoundaryBox(this.boundary)+ }}public refresh() {@@ -512,7 +524,7 @@ export class OrMap extends LitElement {}if (this._mapContainer && this._slotElement) {- this._map = new MapWidget(this.type, this.showGeoCodingControl, this.shadowRoot!, this._mapContainer)+ this._map = new MapWidget(this.type, this.showGeoCodingControl, this.shadowRoot!, this._mapContainer, this.showBoundaryBoxControl, this.useZoomControl).setCenter(this.center).setZoom(this.zoom).setControls(this.controls);diff --git a/ui/component/or-map/src/mapwidget.ts b/ui/component/or-map/src/mapwidget.tsindex 3676ad2f2..9d216b855 100644--- a/ui/component/or-map/src/mapwidget.ts+++ b/ui/component/or-map/src/mapwidget.ts@@ -1,26 +1,39 @@import manager from "@openremote/core";-import maplibregl, {LngLatLike, Map as MapGL, MapboxOptions as OptionsGL, Marker as MarkerGL, Style as StyleGL, LngLat,+import maplibregl,{+ Control,+ GeolocateControl,+ IControl,+ LngLat,+ LngLatLike,+ Map as MapGL,+ MapboxOptions as OptionsGL,MapMouseEvent,+ Marker as MarkerGL,NavigationControl,- GeolocateControl,- Control,- IControl} from "maplibre-gl";+ Style as StyleGL,+} from "maplibre-gl";import MaplibreGeocoder from "@maplibre/maplibre-gl-geocoder";-import '@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css';-import {debounce} from "lodash";-import {ControlPosition, OrMapClickedEvent, OrMapLoadedEvent, OrMapLongPressEvent, OrMapGeocoderChangeEvent, ViewSettings} from "./index";+import "@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css";+import { debounce } from "lodash";import {- OrMapMarker-} from "./markers/or-map-marker";-import {getLatLngBounds, getLngLat} from "./util";+ ControlPosition,+ OrMapClickedEvent,+ OrMapGeocoderChangeEvent,+ OrMapLoadedEvent,+ OrMapLongPressEvent,+ ViewSettings,+} from "./index";+import { OrMapMarker } from "./markers/or-map-marker";+import { getLatLngBounds, getLngLat } from "./util";import { MapType } from "@openremote/model";+const mapboxJsStyles = require("mapbox.js/dist/mapbox.css");const maplibreGlStyles = require("maplibre-gl/dist/maplibre-gl.css");const maplibreGeoCoderStyles = require("@maplibre/maplibre-gl-geocoder/dist/maplibre-gl-geocoder.css");// TODO: fix any type-const metersToPixelsAtMaxZoom = (meters:number, latitude:number) =>- meters / 0.075 / Math.cos(latitude * Math.PI / 180);+const metersToPixelsAtMaxZoom = (meters: number, latitude: number) =>+ meters / 0.075 / Math.cos(latitude * Math.PI / 180);export class MapWidget {@@ -36,15 +49,19 @@ export class MapWidget {protected _center?: LngLatLike;protected _zoom?: number;protected _showGeoCodingControl: boolean = false;+ protected _showBoundaryBox: boolean = false;+ protected _useZoomControls: 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) {+ constructor(type: MapType, showGeoCodingControl: boolean, styleParent: Node, mapContainer: HTMLElement, showBoundaryBox = false, useZoomControls = true) {this._type = type;this._styleParent = styleParent;this._mapContainer = mapContainer;this._showGeoCodingControl = showGeoCodingControl;+ this._showBoundaryBox = showBoundaryBox;+ this._useZoomControls= useZoomControls;}public setCenter(center?: LngLatLike): this {@@ -179,7 +196,9 @@ export class MapWidget {if (this._mapGl) {this._mapGl.setMinZoom(this._viewSettings.minZoom);this._mapGl.setMaxZoom(this._viewSettings.maxZoom);- this._mapGl.setMaxBounds(this._viewSettings.bounds);+ if (this._viewSettings.bounds){+ this._mapGl.setMaxBounds(this._viewSettings.bounds);+ }}if (!this._center) {this.setCenter(this._viewSettings.center);@@ -212,8 +231,11 @@ export class MapWidget {// JS zoom is out compared to GLoptions.zoom = this._viewSettings.zoom ? this._viewSettings.zoom + 1 : undefined;- options.maxZoom = this._viewSettings.maxZoom ? this._viewSettings.maxZoom - 1 : undefined;- options.minZoom = this._viewSettings.minZoom ? this._viewSettings.minZoom + 1 : undefined;++ if (this._useZoomControls){+ options.maxZoom = this._viewSettings.maxZoom ? this._viewSettings.maxZoom - 1 : undefined;+ options.minZoom = this._viewSettings.minZoom ? this._viewSettings.minZoom + 1 : undefined;+ }options.boxZoom = this._viewSettings.boxZoom;// JS uses lat then lng unlike GL@@ -273,9 +295,14 @@ export class MapWidget {};if (this._viewSettings) {- options.minZoom = this._viewSettings.minZoom;- options.maxZoom = this._viewSettings.maxZoom;- options.maxBounds = this._viewSettings.bounds;+ if (this._useZoomControls){+ options.maxZoom = this._viewSettings.maxZoom+ options.minZoom = this._viewSettings.minZoom+ }+ if (this._viewSettings.bounds && !this._showBoundaryBox){+ options.maxBounds = this._viewSettings.bounds;+ }+options.boxZoom = this._viewSettings.boxZoom;options.zoom = this._viewSettings.zoom;options.center = this._viewSettings.center;@@ -390,6 +417,7 @@ export class MapWidget {this._mapContainer.dispatchEvent(new OrMapLoadedEvent());this._loaded = true;+ this.createBoundaryBox()}protected styleLoaded(): Promise<void> {@@ -542,42 +570,92 @@ export class MapWidget {protected _createMarkerRadius(marker:OrMapMarker){if(this._mapGl && this._loaded && marker.radius && marker.lat && marker.lng){- this._removeMarkerRadius(marker);-- this._mapGl.addSource('circleData', {- type: 'geojson',- data: {- type: 'FeatureCollection',- features: [{- type: "Feature",- geometry: {- "type": "Point",- "coordinates": [marker.lng, marker.lat]- },- properties: {- "title": "You Found Me",- }- }]- }- });-- this._mapGl.addLayer({- "id": "marker-radius-circle",- "type": "circle",- "source": "circleData",- "paint": {- "circle-radius": {- stops: [- [0, 0],- [20, metersToPixelsAtMaxZoom(marker.radius, marker.lat)]- ],- base: 2+ this._removeMarkerRadius(marker);++ this._mapGl.addSource('circleData', {+ type: 'geojson',+ data: {+ type: 'FeatureCollection',+ features: [{+ type: "Feature",+ geometry: {+ "type": "Point",+ "coordinates": [marker.lng, marker.lat]},- "circle-color": "red",- "circle-opacity": 0.3- }- });+ properties: {+ "title": "You Found Me",+ }+ }]+ }+ });++ this._mapGl.addLayer({+ "id": "marker-radius-circle",+ "type": "circle",+ "source": "circleData",+ "paint": {+ "circle-radius": {+ stops: [+ [0, 0],+ [20, metersToPixelsAtMaxZoom(marker.radius, marker.lat)]+ ],+ base: 2+ },+ "circle-color": "red",+ "circle-opacity": 0.3+ }+ });+ }+ }++ public createBoundaryBox(boundsArray: string[] = []){+ if(this._mapGl && this._loaded && this._showBoundaryBox && this._viewSettings?.bounds){++ if (this._mapGl.getSource('bounds')) {+ this._mapGl.removeLayer('bounds');+ this._mapGl.removeSource('bounds');}++ if (boundsArray.length !== 4){+ boundsArray = this._viewSettings?.bounds.toString().split(",")+ }+ var req = [+ [+ [boundsArray[0], boundsArray[3]],+ [boundsArray[2], boundsArray[3]],+ [boundsArray[2], boundsArray[1]],+ [boundsArray[0], boundsArray[1]],+ ]+ ]+ this._mapGl.fitBounds([+ parseFloat(boundsArray[0]) + .01,+ parseFloat(boundsArray[1]) - .01,+ parseFloat(boundsArray[2]) - .01,+ parseFloat(boundsArray[3]) + .01,+ ])+ this._mapGl.addSource('bounds', {+ 'type': 'geojson',+ 'data': {+ 'type': 'Feature',+ 'properties': {},+ 'geometry': {+ 'type': 'Polygon',+ // @ts-ignore+ 'coordinates': req+ }+ }+ });++ this._mapGl.addLayer({+ 'id': 'bounds',+ 'type': 'fill',+ 'source': 'bounds',+ 'paint': {+ 'fill-color': '#FF0000',+ 'fill-opacity': .4+ }+ });+ }}protected _addMarkerClickHandler(marker: OrMapMarker, elem: HTMLElement) {@@ -677,4 +755,4 @@ export class MapWidget {protected _onGeocodeChange(geocode:any) {this._mapContainer.dispatchEvent(new OrMapGeocoderChangeEvent(geocode));}-}\ No newline at end of file+}