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
UI update: major update to or-map and markers
Rich Turnere992ce8c7029
diff --git a/ui/component/or-map/@types/mapbox.js.d.ts b/ui/component/or-map/@types/mapbox.js.d.tsindex 7544a4029..393b41631 100644--- a/ui/component/or-map/@types/mapbox.js.d.ts+++ b/ui/component/or-map/@types/mapbox.js.d.ts@@ -1,15 +1,42 @@+/* tslint:disable:class-name */declare module "mapbox.js" {+ export type Point2d = [number, number];+ export type Point3d = [number, number, number];++ export type LatLngLike = Point2d | Point3d | LatLng;+ export type LatLngBoundsLike = [LatLngLike, LatLngLike] | LatLngBounds;+export default L;- type Point2d = [number, number];- type Point3d = [number, number, number];+ export class LatLng {+ public alt?: number;+ public lat: number;+ public lng: number;+ private constructor(lat: number, lng: number, alt?: number);+ }++ export class LatLngBounds {+ private constructor();+ public getSouthEast(): LatLng;+ public getNorthWest(): LatLng;+ public getNorthEast(): LatLng;+ public getSouthWest(): LatLng;+ public getCenter(): LatLng;+ }- type LatLngLike = Point2d | Point3d | LatLng;- type LatLngBoundsLike = [LatLngLike, LatLngLike] | LatLngBounds;+ export class Map {+ private constructor();+ public getBoundsZoom(bounds: LatLngBoundsLike, inside?: boolean): number;+ public setMaxZoom(zoom: number): this;+ public setMinZoom(zoom: number): this;+ public getContainer(): HTMLElement;+ public setView(center: LatLngLike, zoom?: number, options?: ZoomPanOptions): this;+ public setZoom(zoom: number, options?: ZoomOptions): this;+ }export interface MapOptions {- zoom?: number,+ zoom?: number;boxZoom?: boolean;center?: LatLngLike;maxBounds?: LatLngBoundsLike;@@ -18,22 +45,22 @@ declare module "mapbox.js" {}export interface IconOptions {- iconUrl?: string,- iconRetinaUrl?: string,- iconSize?: Point2d,- iconAnchor?: Point2d,- popupAnchor?: Point2d,- tooltipAnchor?: Point2d,- shadowUrl?: string,- shadowRetinaUrl?: string,- shadowSize?: Point2d,- shadowAnchor?: Point2d,- className?: string+ iconUrl?: string;+ iconRetinaUrl?: string;+ iconSize?: Point;+ iconAnchor?: Point;+ popupAnchor?: Point;+ tooltipAnchor?: Point;+ shadowUrl?: string;+ shadowRetinaUrl?: string;+ shadowSize?: Point;+ shadowAnchor?: Point;+ className?: string;}export interface DivIconOptions extends IconOptions {- html?: string,- bgPos?: Point2d+ html?: string;+ bgPos?: Point;}export interface MarkerOptions {@@ -43,57 +70,62 @@ declare module "mapbox.js" {alt?: string;zIndexOffset?: number;opacity?: number;+ clickable?: boolean;}- export class LatLng {- private constructor();+ export interface ZoomOptions {+ animate?: boolean;+ }- lat: number;- lng: number;- alt?: number;+ export interface PanOptions extends ZoomOptions {+ duration?: number;+ easeLinearity?: number;+ noMoveStart?: boolean;}- export class LatLngBounds {- private constructor();- getSouthEast(): LatLng;- getNorthWest(): LatLng;- getNorthEast(): LatLng;- getSouthWest(): LatLng;- getCenter(): LatLng;+ export interface ZoomPanOptions extends ZoomOptions {+ reset?: boolean;+ pan?: PanOptions;+ zoom?: ZoomOptions;}- export class Icon {+ export interface Icon {}- export class DivIcon extends Icon {+ export interface DivIcon extends Icon {}+ export interface Point {+ x: number;+ y: number;+ }+export class Marker extends Layer {- setLatLng(latLng: LatLngLike): this;- on(event: any, func: any): this;+ public setLatLng(latLng: LatLngLike): this;+ public on(event: any, func: any): this;+ public off(event: any, func?: any): this;+ public getElement(): HTMLElement;}class Layer {- addTo(addTo: L.mapbox.map): this;- removeFrom(removeFrom: L.mapbox.map): this;+ public addTo(addTo: Map): this;+ public removeFrom(removeFrom: Map): this;}- export namespace L {+ namespace L {+namespace mapbox {- export class map {- constructor(element: string | Element, tilejson: object, options?: MapOptions);- getBoundsZoom(bounds: LatLngBoundsLike, inside?: boolean): number;- setMaxZoom(zoom: number): this;- setMinZoom(zoom: number): this;- }+ function map(element: string | Element, tilejson: object, options?: MapOptions): Map;}function icon(options: IconOptions): Icon;function divIcon(options: DivIconOptions): DivIcon;+ function point(x: number, y: number): Point;+function latLng(lat: number, lng: number, alt?: number): LatLng;function latLng(pos: LatLngLike): LatLng;@@ -104,4 +136,4 @@ declare module "mapbox.js" {function marker(pos: LatLngLike, options: MarkerOptions): Marker;}-}\ No newline at end of file+}diff --git a/ui/component/or-map/README.md b/ui/component/or-map/README.mdindex dc84a34e4..883789246 100644--- a/ui/component/or-map/README.md+++ b/ui/component/or-map/README.md@@ -16,6 +16,25 @@ npm i -S @openremote/or-mapTODO+```{html}+ /**+ * By default this generates the following marker HTML:+ * <div class="or-map-marker">+ * <CHILD NODE>+ * <CHILD NODE>+ * </div>+ *+ * If there are no child nodes then the default or-map-marker is+ * used:+ * <div class="or-map-marker or-map-marker-default">+ * <div>+ * <or-icon icon="or:marker"></or-icon>+ * <or-icon class="marker-icon" icon="${icon || ""}"></or-icon>+ * </div>+ * </div>+ */+```+## License[GNU AGPL](https://www.gnu.org/licenses/agpl-3.0.en.html)diff --git a/ui/component/or-map/src/index.ts b/ui/component/or-map/src/index.tsindex e199b6b60..a636d74df 100644--- a/ui/component/or-map/src/index.ts+++ b/ui/component/or-map/src/index.ts@@ -1,31 +1,31 @@import openremote, {EventCallback, OREvent} from "@openremote/core";-import {html, PolymerElement} from "@polymer/polymer";-import { FlattenedNodesObserver } from '@polymer/polymer/lib/utils/flattened-nodes-observer.js';-import {customElement, property} from '@polymer/decorators';-import {OrMapMarker} from "./markers/or-map-marker";-+import {FlattenedNodesObserver} from "@polymer/polymer/lib/utils/flattened-nodes-observer.js";+import {css, customElement, html, LitElement, property, query} from "lit-element";+import {LngLat, LngLatBoundsLike, LngLatLike} from "mapbox-gl";import {MapWidget} from "./mapwidget";+import {+ OrMapMarker, OrMapMarkerEvent, OrMapMarkerChangedEvent+} from "./markers/or-map-marker";+import {getLngLat} from "./util";export enum Type {VECTOR = "VECTOR",RASTER = "RASTER"}-/**- * `or-map`- * Displays a map- *- */-@customElement('or-map')-export class OrMap extends PolymerElement {- protected _initCallback?: EventCallback;- protected _map?: MapWidget;- protected _loaded: boolean = false;- protected _observer?: FlattenedNodesObserver;+export interface ViewSettings {+ "center": LngLatLike;+ "bounds": LngLatBoundsLike;+ "zoom": number;+ "maxZoom": number;+ "minZoom": number;+ "boxZoom": boolean;+}- static get template() {- return html`- <style>+@customElement("or-map")+export class OrMap extends LitElement {++ public static styles = css`:host {display: block;overflow: hidden;@@ -38,64 +38,117 @@ export class OrMap extends PolymerElement {slot {display: none;}- .marker {- background-image: url('http://pngimg.com/uploads/smiley/smiley_PNG36233.png');++ :host([hidden]) {+ display: none;+ }++ .leaflet-marker-icon, .mapboxgl-marker {+ pointer-events: none !important;+ }++ /* Offset margin set by leaflet-marker-icon */+ .leaflet-marker-icon .or-map-marker {+ margin-left: 6px;+ margin-top: 6px;+ }++ .or-map-marker {+ position: absolute; /* This makes mapboxJS behave like mapboxGL */+ cursor: grab;+ }++ .or-map-marker.interactive {+ cursor: pointer;+ }++ .or-map-marker>*{+ pointer-events: visible;+ }++ .or-map-marker-default {+ position: relative;+ transform: var(--or-map-marker-transform, translate(-24px, -45px));+ --or-icon-width: var(--or-map-marker-width, 48px);+ --or-icon-height: var(--or-map-marker-height, 48px);+ --or-icon-fill-color: var(--or-map-marker-fill, #1D5632);+ }++ .or-map-marker-default .marker-icon {position: absolute;- width: 32px;- height: 32px;- background-size: 32px;+ left: 50%;+ top: 0px;+ --or-icon-fill-color: var(--or-map-marker-icon-fill, #FFF);+ --or-icon-width: var(--or-map-marker-icon-width, 24px);+ --or-icon-height: var(--or-map-marker-icon-height, 24px);+ transform: var(--or-map-marker-icon-transform, translate(-50%, 5px));}- </style>- <div id="map"></div>- <slot id="markers-slot"></slot>`;- }@property({type: String})- type: Type = Type.VECTOR;+ public type: Type = Type.VECTOR;- constructor() {- super();- }+ @property({type: String, converter: {+ fromAttribute(value: string | null, type?: String): LngLatLike | undefined {+ if (!value) {+ return;+ }- _processNewMarkers(nodes : Element[]) {- nodes.forEach((node) => {- if (!this._map) {- return;- }+ const coords = value.split(",");+ if (coords.length !== 2) {+ return;+ }+ const lng = Number(coords[0]);+ const lat = Number(coords[1]);+ return new LngLat(lng, lat);+ },- if(node instanceof OrMapMarker) {- node.map = this._map;- }- });- }+ toAttribute(value?: LngLatLike, type?: String): string {+ const lngLat = getLngLat(value);- _processRemovedMarkers(nodes : Element[]) {- nodes.forEach((node) => {- if (!this._map) {- return;+ if (!lngLat) {+ return "";+ }++ return "" + lngLat.lng + "," + lngLat.lat;}+ }})+ public center?: LngLatLike;+ @property({type: Number})+ public zoom?: number;- if(node instanceof OrMapMarker) {- node.map = undefined;- }- });+ protected _initCallback?: EventCallback;+ protected _map?: MapWidget;+ protected _loaded: boolean = false;+ protected _observer?: FlattenedNodesObserver;++ @query("#map")+ protected _mapContainer?: HTMLElement;++ @query("slot")+ protected _slotElement?: HTMLSlotElement;++ constructor() {+ super();+ this.addEventListener(OrMapMarkerEvent.CHANGED, this._onMarkerChangedEvent);}- disconnectedCallback() {+ public disconnectedCallback() {super.disconnectedCallback();this._observer!.disconnect();}- ready() {- super.ready();+ public connectedCallback() {+ super.connectedCallback();if (!openremote.ready) {// Defer until openremote is initialisedthis._initCallback = (initEvent) => {if (initEvent === OREvent.READY) {this.loadMap();++ openremote.removeListener(this._initCallback!);}};openremote.addListener(this._initCallback);@@ -104,20 +157,20 @@ export class OrMap extends PolymerElement {}}- loadMap() {+ public loadMap() {if (this._loaded) {return;}- if (this.shadowRoot) {- const mapElement: HTMLElement = this.shadowRoot.getElementById('map')!;+ if (this._mapContainer && this._slotElement) {- this._map = new MapWidget(this.type, this.shadowRoot, mapElement);+ this._map = new MapWidget(this.type, this.shadowRoot!, this._mapContainer)+ .setCenter(this.center)+ .setZoom(this.zoom);this._map.load().then(() => {// Get markers from slot- let slotElement = this.shadowRoot!.getElementById('markers-slot');- this._observer = new FlattenedNodesObserver(slotElement!, (info: any) => {+ this._observer = new FlattenedNodesObserver(this._slotElement!, (info: any) => {this._processNewMarkers(info.addedNodes);this._processRemovedMarkers(info.removedNodes);});@@ -126,4 +179,41 @@ export class OrMap extends PolymerElement {this._loaded = true;}++ protected _onMarkerChangedEvent(evt: OrMapMarkerChangedEvent) {+ if (this._map) {+ this._map.onMarkerChanged(evt.detail.marker, evt.detail.property);+ }+ }++ protected _processNewMarkers(nodes: Element[]) {+ nodes.forEach((node) => {+ if (!this._map) {+ return;+ }++ if (node instanceof OrMapMarker) {+ this._map.addMarker(node);+ }+ });+ }++ protected _processRemovedMarkers(nodes: Element[]) {+ nodes.forEach((node) => {+ if (!this._map) {+ return;+ }++ if (node instanceof OrMapMarker) {+ this._map.removeMarker(node);+ }+ });+ }++ protected render() {+ return html`+ <div id="map"></div>+ <slot></slot>+ `;+ }}diff --git a/ui/component/or-map/src/mapwidget.ts b/ui/component/or-map/src/mapwidget.tsindex e4f27a7d4..9976e816f 100644--- a/ui/component/or-map/src/mapwidget.ts+++ b/ui/component/or-map/src/mapwidget.ts@@ -1,38 +1,78 @@-import L, {MapOptions, Marker} from "mapbox.js";-import {Type} from "./index";-import rest from "@openremote/rest";import openremote from "@openremote/core";-import {Map as MapGL, MapboxOptions, Style as MapboxStyle, Marker as MarkerGL} from "mapbox-gl";-import {OrMapMarker} from "./markers/or-map-marker";+import rest from "@openremote/rest";+import {LngLatLike, Map as MapGL, MapboxOptions as OptionsGL, Marker as MarkerGL, Style as StyleGL, LngLat, MapEventType,+ MapMouseEvent} from "mapbox-gl";+import L, {Map as MapJS, MapOptions as OptionsJS, Marker as MarkerJS} from "mapbox.js";+import {Type, ViewSettings} from "./index";+import {OrMapMarker, OrMapMarkerClickedEvent} from "./markers/or-map-marker";+import {getLatLng, getLatLngBounds, getLngLat, getLngLatBounds} from "./util";export class MapWidget {- protected _mapJs?: L.mapbox.map;- protected _mapGl?: MapGL;protected static _mapboxGlStyle?: any;protected static _mapboxJsStyle?: any;+ protected _mapJs?: MapJS;+ protected _mapGl?: MapGL;protected _type: Type;protected _styleParent: Node;protected _mapContainer: HTMLElement;protected _loaded: boolean = false;- protected _markersJs?: Map<OrMapMarker, Marker>;- protected _markersGl?: Map<OrMapMarker, MarkerGL>;+ protected _markersJs: Map<OrMapMarker, MarkerJS> = new Map();+ protected _markersGl: Map<OrMapMarker, MarkerGL> = new Map();+ protected _viewSettings?: ViewSettings;+ protected _center?: LngLat;+ protected _zoom?: number;+ protected _clickHandlers: Map<OrMapMarker, (ev: MouseEvent) => void> = new Map();constructor(type: Type, styleParent: Node, mapContainer: HTMLElement) {this._type = type;this._styleParent = styleParent;this._mapContainer = mapContainer;+ }- switch(type) {+ public setCenter(center?: LngLatLike): this {++ this._center = getLngLat(center);++ switch (this._type) {case Type.RASTER:- this._markersJs = new Map<OrMapMarker, Marker>();+ if (this._mapJs) {+ const latLng = getLatLng(this._center) || (this._viewSettings ? getLatLng(this._viewSettings.center) : undefined);+ if (latLng) {+ this._mapJs.setView(latLng, undefined, {pan: {animate: false}, zoom: {animate: false}});+ }+ }break;case Type.VECTOR:- this._markersGl = new Map<OrMapMarker, MarkerGL>();+ if (this._mapGl && this._center) {+ this._mapGl.setCenter(this._center);+ }break;}++ return this;}- async load(): Promise<void> {+ public setZoom(zoom?: number): this {++ this._zoom = zoom;++ switch (this._type) {+ case Type.RASTER:+ if (this._mapJs && this._zoom) {+ this._mapJs.setZoom(this._zoom, {animate: false});+ }+ break;+ case Type.VECTOR:+ if (this._mapGl && this._zoom) {+ this._mapGl.setZoom(this._zoom);+ }+ break;+ }++ return this;+ }++ public async load(): Promise<void> {if (this._loaded) {return;}@@ -43,46 +83,42 @@ export class MapWidget {if (!MapWidget._mapboxJsStyle) {// @ts-ignore- MapWidget._mapboxJsStyle = await import("mapbox.js/dist/mapbox.css");+ MapWidget._mapboxJsStyle = await import(/* webpackChunkName: "mapbox-js-css" */ "mapbox.js/dist/mapbox.css");}// Add style to shadow root- var style = document.createElement('style');+ const style = document.createElement("style");style.id = "mapboxJsStyle";style.textContent = MapWidget._mapboxJsStyle.default.toString();this._styleParent.appendChild(style);const settingsResponse = await rest.api.MapResource.getSettingsJs();- const settings = <any> settingsResponse.data;+ const settings = settingsResponse.data as any;// Load options for current realm or fallback to default if exist- let settingOptions : any = settings.options ? settings.options[openremote.getRealm() || "default"] ? settings.options[openremote.getRealm() || "default"] : settings.options.default : null;- let options: MapOptions | undefined;- if (settingOptions) {+ this._viewSettings = settings.options ? settings.options[openremote.getRealm() || "default"] ? settings.options[openremote.getRealm() || "default"] : settings.options.default : null;+ let options: OptionsJS | undefined;+ if (this._viewSettings) {options = {};- // JS zoom is out by one compared to GL- options.zoom = settingOptions.zoom ? settingOptions.zoom + 1 : undefined;- options.maxZoom = settingOptions.maxZoom;- options.minZoom = settingOptions.minZoom;- options.boxZoom = settingOptions.boxZoom;+ // JS zoom is out compared to GL+ options.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;+ options.boxZoom = this._viewSettings.boxZoom;// JS uses lat then lng unlike GL- if (settingOptions.bounds) {- let b = settingOptions.bounds;- options.maxBounds = [- [b[1], b[0]],- [b[3], b[2]],- ];- }- if (settingOptions.center) {- let c = settingOptions.center;- options.center = [- c[1], c[0]- ];+ if (this._viewSettings.bounds) {+ options.maxBounds = getLatLngBounds(this._viewSettings.bounds);+ }+ if (this._viewSettings.center) {+ options.center = getLatLng(this._viewSettings.center);+ }+ if (this._center) {+ options.center = getLatLng(this._center);}}- this._mapJs = new L.mapbox.map(this._mapContainer, settings, options);+ this._mapJs = L.mapbox.map(this._mapContainer, settings, options);if (options && options.maxBounds) {const minZoom = this._mapJs.getBoundsZoom(options.maxBounds, true);@@ -94,94 +130,186 @@ export class MapWidget {} else {if (!MapWidget._mapboxGlStyle) {// @ts-ignore- MapWidget._mapboxGlStyle = await import("mapbox-gl/dist/mapbox-gl.css");+ MapWidget._mapboxGlStyle = await import(/* webpackChunkName: "mapbox-gl-css" */ "mapbox-gl/dist/mapbox-gl.css");}// Add style to shadow root- const style = document.createElement('style');+ const style = document.createElement("style");style.id = "mapboxGlStyle";style.textContent = MapWidget._mapboxGlStyle.default.toString();this._styleParent.appendChild(style);- const map: typeof import("mapbox-gl") = await import("mapbox-gl");+ const map: typeof import("mapbox-gl") = await import(/* webpackChunkName: "mapbox-gl" */ "mapbox-gl");const settingsResponse = await rest.api.MapResource.getSettings();- const settings = <any> settingsResponse.data;+ const settings = settingsResponse.data as any;// Load options for current realm or fallback to default if exist- let settingOptions : any = settings.options ? settings.options[openremote.getRealm() || "default"] ? settings.options[openremote.getRealm() || "default"] : settings.options.default : null;- let options: MapboxOptions = {- container: this._mapContainer,- style: <MapboxStyle> settings,+ this._viewSettings = settings.options ? settings.options[openremote.getRealm() || "default"] ? settings.options[openremote.getRealm() || "default"] : settings.options.default : null;+ const options: OptionsGL = {attributionControl: true,+ container: this._mapContainer,+ style: settings as StyleGL,transformRequest: (url, resourceType) => {return {- url: url,- headers: {'Authorization': openremote.getAuthorizationHeader()}- }+ headers: {Authorization: openremote.getAuthorizationHeader()},+ url+ };}};- if (settingOptions) {- options.minZoom = settingOptions.minZoom;- options.maxZoom = settingOptions.maxZoom;- options.maxBounds = settingOptions.bounds;- options.boxZoom = settingOptions.boxZoom;- options.zoom = settingOptions.zoom;- options.center = settingOptions.center;+ if (this._viewSettings) {+ options.minZoom = this._viewSettings.minZoom;+ options.maxZoom = this._viewSettings.maxZoom;+ options.maxBounds = this._viewSettings.bounds;+ options.boxZoom = this._viewSettings.boxZoom;+ options.zoom = this._viewSettings.zoom;+ options.center = this._viewSettings.center;+ }+ if (this._center) {+ options.center = this._center;}this._mapGl = new map.Map(options);}}- addMarker(marker: OrMapMarker) {- if (marker._ele) {- switch (this._type) {- case Type.RASTER:- let icon = L.divIcon({className: 'map-marker', html: marker._ele.outerHTML});- let m: Marker = L.marker([marker.lat, marker.lng], {icon: icon});-- m.addTo(this._mapJs!);+ public addMarker(marker: OrMapMarker) {+ this._updateMarkerElement(marker, true);+ }- if(marker._onClick) {- m.on('click', marker._onClick);- }+ public removeMarker(marker: OrMapMarker) {+ this._updateMarkerElement(marker, false);+ }- this._markersJs!.set(marker, m);- break;- case Type.VECTOR:- new MarkerGL(marker._ele)- .setLngLat([marker.lng, marker.lat])- .addTo(this._mapGl!);- break;- }+ public onMarkerChanged(marker: OrMapMarker, prop: string) {+ switch (prop) {+ case "icon":+ this._updateMarkerElement(marker, true);+ break;+ case "lat":+ case "lng":+ this._updateMarkerPosition(marker);+ break;+ case "visible":+ this._updateMarkerVisibility(marker);+ break;}}- removeMarker(marker: OrMapMarker) {+ protected _updateMarkerPosition(marker: OrMapMarker) {switch (this._type) {case Type.RASTER:- let m: Marker | undefined = this._markersJs!.get(marker);+ const m: MarkerJS | undefined = this._markersJs.get(marker);if (m) {- this._markersJs!.delete(marker);- m.removeFrom(this._mapJs!);+ m.setLatLng([marker.lat, marker.lng]);}break;case Type.VECTOR:+ const mGl: MarkerGL | undefined = this._markersGl.get(marker);+ if (mGl) {+ mGl.setLngLat([marker.lng, marker.lat]);+ }break;}}- updateMarkerPosition(marker: OrMapMarker) {+ protected _updateMarkerVisibility(marker: OrMapMarker) {switch (this._type) {case Type.RASTER:- let m: Marker | undefined = this._markersJs!.get(marker);+ const m: MarkerJS | undefined = this._markersJs.get(marker);+ if (m && m.getElement()) {+ if (marker.visible) {+ m.getElement().removeAttribute("hidden");+ } else {+ m.getElement().setAttribute("hidden", "true");+ }+ }+ break;+ case Type.VECTOR:+ const mGl: MarkerGL | undefined = this._markersGl.get(marker);+ if (mGl) {+ if (marker.visible) {+ mGl.getElement().removeAttribute("hidden");+ } else {+ mGl.getElement().setAttribute("hidden", "true");+ }+ }+ break;+ }+ }++ protected _updateMarkerElement(marker: OrMapMarker, doAdd: boolean) {++ switch (this._type) {+ case Type.RASTER:+ let m = this._markersJs.get(marker);if (m) {- m.setLatLng([marker.lat, marker.lng]);+ m.removeFrom(this._mapJs!);+ this._markersJs.delete(marker);+ this._removeMarkerClickHandler(marker, m.getElement());+ }++ if (doAdd) {+ const elem = marker.createMarkerElement();+ if (elem) {+ const icon = L.divIcon({html: elem.outerHTML, className: "or-marker-raster"});+ m = L.marker([marker.lat, marker.lng], {icon: icon, clickable: marker.interactive});+ m.addTo(this._mapJs!);++ if (marker.interactive) {+ this._addMarkerClickHandler(marker, m.getElement());+ }++ this._markersJs.set(marker, m);+ this._updateMarkerVisibility(marker);+ }}break;case Type.VECTOR:+ let mGl = this._markersGl.get(marker);+ if (mGl) {+ mGl.remove();+ this._markersGl.delete(marker);+ this._removeMarkerClickHandler(marker, mGl.getElement());+ }++ if (doAdd) {+ const elem = marker.createMarkerElement();++ if (elem) {+ mGl = new MarkerGL({+ element: elem,+ anchor: "top-left"+ })+ .setLngLat([marker.lng, marker.lat])+ .addTo(this._mapGl!);++ this._markersGl.set(marker, mGl);+ this._updateMarkerVisibility(marker);++ if (marker.interactive) {+ this._addMarkerClickHandler(marker, mGl.getElement());+ }+ }+ }break;}}-}\ No newline at end of file++ protected _addMarkerClickHandler(marker: OrMapMarker, elem: HTMLElement) {+ const handler = (ev: MouseEvent) => {+ ev.stopPropagation();+ marker._onClick(ev);+ };+ this._clickHandlers.set(marker, handler);+ elem.addEventListener("click", handler);+ }++ protected _removeMarkerClickHandler(marker: OrMapMarker, elem: HTMLElement) {+ const handler = this._clickHandlers.get(marker);+ if (handler) {+ elem.removeEventListener("click", handler);+ this._clickHandlers.delete(marker);+ }+ }+}diff --git a/ui/component/or-map/src/markers/or-map-marker-asset.ts b/ui/component/or-map/src/markers/or-map-marker-asset.tsindex d53d66328..04afc3813 100644--- a/ui/component/or-map/src/markers/or-map-marker-asset.ts+++ b/ui/component/or-map/src/markers/or-map-marker-asset.ts@@ -1,5 +1,4 @@-import {html} from "@polymer/polymer";-import {customElement, property, observe} from "@polymer/decorators";+import {customElement, property} from "lit-element";import {OrMapMarker} from "./or-map-marker";import rest from "@openremote/rest";import {Asset, AssetAttribute, GeoJSONPoint} from "@openremote/model";@@ -13,7 +12,7 @@ import {GenericAxiosResponse} from "axios";@customElement('or-map-marker-asset')export class OrMapMarkerAsset extends OrMapMarker {- @property({type: String, observer: "_assetChanged"})+ @property({type: String})asset?: string;@property({type: Object})@@ -23,7 +22,7 @@ export class OrMapMarkerAsset extends OrMapMarker {super();}- _createMarkerElement(): HTMLElement {+ _getMarkerElement(): HTMLElement {let className = ("or-map-marker " + this.className).trim();let ele = document.createElement("div");ele.className = className;@@ -69,10 +68,6 @@ export class OrMapMarkerAsset extends OrMapMarker {}}- _elementChanged() {- this._updateMarker();- }-private _createAssetMarker() {// Create basic element of _ele is undefinedif(typeof this._ele === 'undefined') {diff --git a/ui/component/or-map/src/markers/or-map-marker.ts b/ui/component/or-map/src/markers/or-map-marker.tsindex 05f952d18..22a64b0e0 100644--- a/ui/component/or-map/src/markers/or-map-marker.ts+++ b/ui/component/or-map/src/markers/or-map-marker.ts@@ -1,116 +1,153 @@-import {html, PolymerElement} from "@polymer/polymer";-import {property, query, observe, customElement} from "@polymer/decorators";-import {MapWidget} from "../mapwidget";+import {css, customElement, LitElement, property, PropertyValues, query, html} from "lit-element";+import {html as litHtml, render} from "lit-html";++export enum OrMapMarkerEvent {+ CLICKED = "or-map-marker-clicked",+ CHANGED = "or-map-marker-changed"+}++declare global {+ export interface HTMLElementEventMap {+ [OrMapMarkerEvent.CHANGED]: OrMapMarkerChangedEvent;+ [OrMapMarkerEvent.CLICKED]: OrMapMarkerClickedEvent;+ }+}++export class OrMapMarkerChangedEvent extends CustomEvent<MarkerChangedEventDetail> {++ constructor(marker: OrMapMarker, prop: string) {+ super(OrMapMarkerEvent.CHANGED, {+ detail: {+ marker: marker,+ property: prop+ },+ bubbles: true,+ composed: true+ });+ }+}++export class OrMapMarkerClickedEvent extends CustomEvent<MarkerEventDetail> {++ constructor(marker: OrMapMarker) {+ super(OrMapMarkerEvent.CLICKED, {+ detail: {+ marker: marker+ },+ bubbles: true,+ composed: true+ });+ }+}++export interface MarkerEventDetail {+ marker: OrMapMarker;+}++export interface MarkerChangedEventDetail extends MarkerEventDetail {+ property: string;+}/**- * Base class for all map markers+ * Base class for all map markers.+ *+ * This component doesn't directly render anything instead it generates DOM that can be added to the map component*/@customElement("or-map-marker")-export class OrMapMarker extends PolymerElement {- protected _added: boolean = false;- protected _attached: boolean = false;+export class OrMapMarker extends LitElement {++ public static styles = css`+ :host {+ display: none;+ }++ slot {+ display: none;+ }+ `;++ protected static _defaultTemplate = (icon: string | undefined) => litHtml`+ <div class="or-map-marker-default">+ <or-icon icon="or:marker"></or-icon>+ <or-icon class="marker-icon" icon="${icon || ""}"></or-icon>+ </div>+ `@property({type: Number})- lat: number = 0;+ public lat: number = 0;@property({type: Number})- lng: number = 0;+ public lng: number = 0;@property({type: Boolean})- visible: boolean = true;+ public visible: boolean = true;- @property({type: Object})- _ele!: HTMLElement;+ @property({type: String})+ public icon?: string;- @property({type: Object})- map?: MapWidget;+ @property({type: Boolean})+ public interactive: boolean = true;@query("slot")- _slot!: HTMLSlotElement;-- static get template() {- return html`- <style>- :host {- display: block;- overflow: hidden;- }- #map {- position: relative;- width: 100%;- height: 100%;- }- slot {- display: none;- }- </style>- <slot></slot>- `;- }+ protected _slot?: HTMLSlotElement;- connectedCallback() {- super.connectedCallback();- this._attached = true;- this._ele = this._createMarkerElement();+ public _onClick(e: MouseEvent) {+ this.dispatchEvent(new OrMapMarkerClickedEvent(this));}- disconnectedCallback() {- super.disconnectedCallback();- this._removeMarker();- this._attached = false;- }-- @observe("visible", "lat", "lng", "map")- _updateMarker() {- if (!this._attached || !this.map) return;-- if (!this._ele) {- this._ele = this._createMarkerElement();+ /**+ * Override in sub types to return custom marker HTML+ */+ public createMarkerElement(): HTMLElement {++ const ele = document.createElement("div");+ this.setMarkerElementClassNames(ele);++ // Append child elements+ let hasChildren = false;++ if (this._slot) {+ this._slot.assignedNodes({flatten: true}).forEach((child) => {+ if (child instanceof HTMLElement) {+ ele.appendChild(child.cloneNode(true));+ hasChildren = true;+ }+ });}-- if (!this._ele) {- return;++ if (!hasChildren) {+ // Append default marker+ this.addDefaultMarkerContent(ele);}- if (!this.visible) {- this._removeMarker();- } else {- this._addMarker();- this.map!.updateMarkerPosition(this);- }+ return ele;}- _addMarker() {- if (!this._added) {- this.map!.addMarker(this);- this._added = true;- }+ protected shouldUpdate(_changedProperties: PropertyValues): boolean {+ Object.keys(_changedProperties).forEach((prop) => this._raisePropertyChange(prop));+ return false;}- _removeMarker() {- if (this._added) {- this.map!.removeMarker(this);- this._added = false;- }+ protected render() {+ return html`+ <slot></slot>+ `;}- //TODO make this optional?- _onClick(e:any) {+ protected _raisePropertyChange(prop: string) {+ this.dispatchEvent(new OrMapMarkerChangedEvent(this, prop));}- _createMarkerElement(): HTMLElement {- let children = this._slot.assignedNodes({flatten:true});- let len = children.length;- let className = ("or-map-marker " + this.className).trim();- let ele = document.createElement("div");- ele.className = className;-- if (len > 0) {- // if more than 1 ele put inside wrapper- for (var i=0; i<len; ++i) {- ele.appendChild(children[i]);- }+ protected setMarkerElementClassNames(markerElement: HTMLElement) {+ let classes = "or-map-marker ";+ if (this.interactive) {+ classes += "interactive ";}- return ele;+ const className = (classes + this.className).trim();+ markerElement.className = className;+ }++ protected addDefaultMarkerContent(markerElement: HTMLElement) {+ render(OrMapMarker._defaultTemplate(this.icon), markerElement);}-}\ No newline at end of file+}diff --git a/ui/demo/demo-or-map/index.html b/ui/demo/demo-or-map/index.htmlindex d1afaa7b9..5064661ba 100644--- a/ui/demo/demo-or-map/index.html+++ b/ui/demo/demo-or-map/index.html@@ -18,6 +18,16 @@<custom-style><style is="custom-style" include="demo-pages-shared-styles">+ #vector {+ --or-map-marker-width: 80px;+ --or-map-marker-height: 80px;+ --or-map-marker-transform: translate(-40px, -75px);+ --or-map-marker-fill: blue;+ --or-map-marker-icon-width: 38px;+ --or-map-marker-icon-height: 38px;+ --or-map-marker-icon-transform: translate(-50%, 9px);+ --or-map-marker-icon-fill: red;+ }</style></custom-style></head>@@ -26,11 +36,11 @@<h3>Demo</h3><demo-snippet><template>- <or-map type="RASTER" style="height: 500px; width: 100%;">- <or-map-marker lat="51.4403423" lng="5.4679712" click-action="showCard" class="marker"></or-map-marker>+ <or-map type="RASTER" center="5.454250, 51.445990" style="height: 500px; width: 100%;">+ <or-map-marker lat="51.445990" lng="5.454250" click-action="showCard" class="marker" icon="or:logo-plain"></or-map-marker></or-map>- <or-map style="height: 500px; width: 100%;">- <or-map-marker lat="51.4403423" lng="5.4679712" click-action="showCard" class="marker"></or-map-marker>+ <or-map id="vector" center="5.454250, 51.445990" style="height: 500px; width: 100%;">+ <or-map-marker lat="51.445990" lng="5.454250" click-action="showCard" class="marker" icon="or:logo-plain"></or-map-marker></or-map></template></demo-snippet>diff --git a/ui/demo/demo-or-map/src/index.ts b/ui/demo/demo-or-map/src/index.tsindex 4262a2296..2137422c4 100644--- a/ui/demo/demo-or-map/src/index.ts+++ b/ui/demo/demo-or-map/src/index.ts@@ -1,8 +1,10 @@-import '@polymer/iron-demo-helpers/demo-pages-shared-styles';-import '@polymer/iron-demo-helpers/demo-snippet';+import "@polymer/iron-demo-helpers/demo-pages-shared-styles";+import "@polymer/iron-demo-helpers/demo-snippet";import "@openremote/or-map";import "@openremote/or-map/dist/markers/or-map-marker";import openremote, {Auth} from "@openremote/core";+import {OrMapMarkerEvent} from "@openremote/or-map/dist/markers/or-map-marker";+import {OrMap} from "@openremote/or-map";openremote.init({auth: Auth.KEYCLOAK,@@ -10,4 +12,22 @@ openremote.init({keycloakUrl: "http://localhost:8080/auth",managerUrl: "http://localhost:8080",realm: "tenantA"+}).then(() => {++ let maps = document.querySelectorAll("or-map");+ let rasterMap = maps[0] as OrMap;+ let vectorMap = maps[1] as OrMap;+ rasterMap.addEventListener(OrMapMarkerEvent.CLICKED, (evt) => {+ console.log("RASTER MAP: Marker clicked: " + JSON.stringify(evt.detail));+ });+ rasterMap.addEventListener("click", (evt) => {+ console.log("RASTER MAP: Map clicked");+ });++ vectorMap.addEventListener(OrMapMarkerEvent.CLICKED, (evt) => {+ console.log("VECTOR MAP: Marker clicked: " + JSON.stringify(evt.detail));+ });+ vectorMap.addEventListener("click", (evt) => {+ console.log("VECTOR MAP: Map clicked");+ });});