Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { DOCUMENT } from '@angular/platform-browser';
- import { Component, Inject, ViewChild, OnInit, AfterViewInit } from '@angular/core';
- import { FormControl } from '@angular/forms';
- import { MdSidenav, MdDialog } from '@angular/material';
- import { TreeComponent, TreeNode, TREE_ACTIONS, IActionMapping } from 'angular2-tree-component';
- import { Accordion } from 'primeng/primeng';
- import { Ol3MapDirective } from './directives/ol3-map.directive';
- import { OwlCarouselDirective } from './directives/owl-carousel.directive';
- import { HttpRequestHelper } from './shared/http-request-helper';
- import { MeasureDialogComponent } from './components/measure-dialog/measure-dialog.component';
- import { MessageDialogComponent } from './components/message-dialog/message-dialog.component';
- import { sprintf, vsprintf } from 'sprintf-js';
- import { Observable } from 'rxjs/Observable';
- import 'rxjs/add/operator/toPromise';
- declare var jQuery: any;
- declare var screenfull: any;
- declare var app: any;
- class Node {
- id: number;
- name: string;
- children?: Node[];
- url?: string;
- urls?: string[];
- isSelected?: boolean;
- extendedSearch: number;
- iconFileId: string;
- options?: {
- visibility: boolean;
- };
- params?: {
- CQL_FILTER: string;
- numZoomLevels: number;
- };
- order: number;
- }
- const actionMapping: IActionMapping = {
- mouse: {
- click: TREE_ACTIONS.TOGGLE_EXPANDED
- }
- };
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.scss']
- })
- export class AppComponent implements OnInit, AfterViewInit {
- @ViewChild('sidenav')
- private _sidenav: MdSidenav;
- @ViewChild('infoSidenav')
- private _infoSidenav: MdSidenav;
- @ViewChild(OwlCarouselDirective)
- private _owlCarousel: OwlCarouselDirective;
- @ViewChild(Accordion)
- private _extendedSearchAccordion: Accordion;
- tabGroupSelectedIndex = 0;
- layersInfos$: Promise<any>;
- searchResults$: Promise<any>;
- extendedSearch$: Promise<any>;
- extendedSearchResult$: Promise<any>;
- extendedSearchModel: { [layerId: string]: Object } = {};
- measureInfo: {
- type: string,
- text: string
- };
- measureInfoTitles: {
- [type: string]: string
- } = {
- 'Point': 'წერტილის კოორდინატები',
- 'LineString': 'სრული სიგრძე',
- 'Polygon': 'სრული ფართობი და პერიმეტრი'
- };
- baseLayer: ol.layer.Tile;
- baseLayerSwitcherVisible = false;
- baseLayerNodes$: Promise<Node[]>;
- overlayLayerNodes$: Promise<Node[]>;
- @ViewChild(TreeComponent)
- private _tree: TreeComponent;
- treeOptions = {
- actionMapping
- };
- @ViewChild(Ol3MapDirective)
- private _ol3Map: Ol3MapDirective;
- private _drawingLayer = new ol.layer.Vector({
- source: new ol.source.Vector({ wrapX: false }),
- style: new ol.style.Style({
- fill: new ol.style.Fill({
- color: 'rgba(255, 255, 255, 0.2)'
- }),
- stroke: new ol.style.Stroke({
- color: '#ffcc33',
- width: 2
- }),
- image: new ol.style.Circle({
- radius: 7,
- fill: new ol.style.Fill({
- color: '#ffcc33'
- })
- })
- })
- });
- private _drawingInteraction: ol.interaction.Draw;
- ol3MapOptions: olx.MapOptions = {
- layers: [
- this._drawingLayer
- ],
- controls: ol.control.defaults({
- rotate: false,
- attribution: false,
- zoom: false
- }).extend([
- new ol.control.Zoom({ zoomInLabel: '', zoomOutLabel: '' }),
- new app.MapToolsControl({
- actions: [{
- icon: 'info',
- title: 'ფენების ინფო',
- handle: () => {
- let interaction = this._addInteraction('Point');
- interaction.on('drawstart', () => {
- this._drawingLayer.getSource().clear();
- });
- interaction.on('drawend', e => {
- this._sidenav.close().then(() => {
- let geometry = e.feature.getGeometry(),
- coordinates3857 = geometry.getCoordinates(),
- coordinates4326 = ol.proj.transform(coordinates3857, 'EPSG:3857', 'EPSG:4326'),
- layerIds = Object.keys(this.checkboxes).filter(id => this.checkboxes[id].isChecked && !!this.layers[id]);
- this._animateTo(coordinates3857, 18);
- this._infoSidenav.close().then(() => {
- if (layerIds.length > 0) {
- let requestBody = {
- sessionId: '12345abcd',
- clientToken: 'aceeb1c1-b378-439e-821a-843abcabaafc',
- params: {
- orgId: 1,
- viewLevel: 1,
- x: coordinates4326[0],
- y: coordinates4326[1],
- lrsIds: layerIds.join(',')
- }
- };
- this.layersInfos$ = this._http.post2('http://192.168.157.38:3000/proxy/tbilisimap-core/api/managelayersws/getLayersInfos', requestBody)
- .toPromise().then(response => response.data);
- this.layersInfos$.then(data => {
- if (data.length > 0) {
- this._infoSidenav.open();
- this._infoSidenav.onClose.first().subscribe(() => {
- this._drawingLayer.getSource().clear();
- });
- }
- });
- } else {
- let dialog = this._dialog.open(MessageDialogComponent, {
- data: {
- message: 'ინფორმაციის ძებნისთვის გთხოვთ ჩართოთ მინიმუმ ერთი დამფარავი ფენა.'
- }
- });
- dialog.afterClosed().subscribe(() => {
- this._drawingLayer.getSource().clear();
- });
- }
- });
- });
- });
- }
- }, {
- icon: 'fullscreen',
- title: 'მთლიანი ეკრანი',
- handle: () => {
- screenfull.toggle(this._doc.body);
- }
- }, {
- icon: 'fullscreen_exit',
- title: 'მთლიანი ეკრანიდან გასვლა',
- handle: () => {
- screenfull.toggle(this._doc.body);
- }
- }, {
- icon: 'place',
- title: 'რუკის საწყისი ხედი',
- handle: () => {
- this._animateTo(ol.proj.transform([44.7805792, 41.7128489], 'EPSG:4326', 'EPSG:3857'));
- }
- }, {
- icon: 'change_history',
- title: 'გაზომვის ხელსაწყოები',
- actions: [{
- icon: 'timeline',
- title: 'სიგრძის გაზომვა',
- handle: () => {
- this._addMesaureTool('LineString', e => {
- let geometry = e.feature.getGeometry();
- this._ol3Map.map.getView().fit(geometry.getExtent(), this._ol3Map.map.getSize());
- // this._dialog.open(MeasureDialogComponent, { data: e });
- // =========================
- let type = geometry.getType(),
- text = sprintf('%d მეტრი',
- MeasureDialogComponent.getLineLength(geometry));
- this._infoSidenav.close().then(() => {
- this.measureInfo = { type, text };
- this._infoSidenav.open();
- });
- });
- }
- }, {
- icon: 'signal_cellular_null',
- title: 'ფართობის გაზომვა',
- handle: () => {
- this._addMesaureTool('Polygon', e => {
- let geometry = e.feature.getGeometry();
- // let g: ol.geom.Polygon = e.feature.getGeometry();
- // g.getLinearRing(0).getFirstCoordinate();
- // this._animateTo(e.feature.getGeometry().getFirstCoordinate(), 16);
- this._ol3Map.map.getView().fit(geometry.getExtent(), this._ol3Map.map.getSize());
- // this._dialog.open(MeasureDialogComponent, { data: e });
- // =========================
- let type = geometry.getType(),
- text = sprintf('ფართობი: %.2f კვადრატული მეტრი, პერიმეტრი: %.2f მეტრი',
- MeasureDialogComponent.getPolygonArea(geometry),
- MeasureDialogComponent.getPolygonLength(geometry));
- this._infoSidenav.close().then(() => {
- this.measureInfo = { type, text };
- this._infoSidenav.open();
- });
- });
- }
- }, {
- icon: 'place',
- title: 'მდებარეობის კოორდინატები',
- handle: () => {
- this._addMesaureTool('Point', e => {
- let geometry = e.feature.getGeometry();
- this._animateTo(geometry.getCoordinates(), 16);
- // this._dialog.open(MeasureDialogComponent, { data: e });
- // =========================
- let type = geometry.getType(),
- text = vsprintf(`X=%s მეტრი Y=%s მეტრი`,
- geometry.getCoordinates().map(c => parseFloat(c).toFixed(0)));
- this._infoSidenav.close().then(() => {
- this.measureInfo = { type, text };
- this._infoSidenav.open();
- });
- });
- }
- }]
- }, {
- icon: 'clear',
- title: 'გრაფიკის გასუფთავება',
- handle: () => {
- this._removeInteraction();
- this._drawingLayer.getSource().clear();
- this._infoSidenav.close();
- }
- }, {
- icon: 'pan_tool',
- title: 'რუკის გადაადგილება',
- handle: () => {
- this._removeInteraction();
- }
- }]
- }),
- new ol.control.MousePosition({
- projection: 'EPSG:4326',
- coordinateFormat: ol.coordinate.createStringXY(4)
- })
- ]),
- view: new ol.View({
- zoom: 14,
- maxZoom: 22,
- center: ol.proj.transform([44.7805792, 41.7128489], 'EPSG:4326', 'EPSG:3857'),
- })
- };
- bxSliderOptions = {
- pager: false,
- infiniteLoop: false
- };
- layers: {
- [id: number]: ol.layer.Tile;
- } = {};
- checkboxes: {
- [id: number]: {
- isChecked: boolean;
- isIndeterminate: boolean;
- };
- } = {};
- options: string[] = [];
- filteredOptions: Observable<string[]>;
- myControl = new FormControl();
- filterOptions(val: string) {
- return this.options.filter(option => new RegExp(val, 'gi').test(option));
- }
- constructor(
- @Inject(DOCUMENT) private _doc: any,
- private _dialog: MdDialog,
- private _http: HttpRequestHelper
- ) {
- this._drawingLayer.setZIndex(1);
- // Possible useful example for the open and closeAll events.
- // Adding a class to the body if a dialog opens and
- // removing it after all open dialogs are closed
- _dialog.afterOpen.subscribe(() => {
- _doc.body.classList.add('no-scroll');
- });
- _dialog.afterAllClosed.subscribe(() => {
- _doc.body.classList.remove('no-scroll');
- });
- }
- ngOnInit() {
- const randomId = () => Math.floor(new Date().valueOf() * Math.random());
- const parseLayer = layer => ({
- id: layer.lrId,
- name: layer.name,
- order: layer.lrOrder,
- url: layer.sourceUrl,
- urls: layer.sourceUrls ? layer.sourceUrls.split(',') : layer.sourceUrls,
- isSelected: !!layer.isSelected,
- extendedSearch: layer.extendedSearch,
- iconFileId: layer.iconFileId,
- options: Object.assign({}, layer.optionsJson),
- params: Object.assign(layer.cqlFilterOl3 || {}, layer.paramsJson) // eval(`(${layer.cql})`) ||
- });
- const parseGroup = group => ({
- id: randomId(),
- name: group.groupName,
- children: group.groups.map(parseGroup)
- .concat(group.lrs.map(parseLayer))
- });
- let requestBody = {
- clientToken: 'aceeb1c1-b378-439e-821a-843abcabaafc',
- params: {
- orgId: 1,
- viewLevel: 1
- }
- };
- let layersObservable = this._http.post2('http://192.168.157.38:3000/proxy/tbilisimap-core/api/managelayersws/getLayersInGroups', requestBody)
- .map(response => response.data.map(parseGroup))
- .toPromise();
- this.baseLayerNodes$ = layersObservable
- .then(response => response[0].children.filter(v => !v.params.type));
- this.overlayLayerNodes$ = layersObservable
- .then(response => response[1].children);
- this.myControl.valueChanges.subscribe(value => {
- this._tree.treeModel.filterNodes(node => node.data.name.indexOf(value) >= 0);
- });
- }
- ngAfterViewInit() {
- jQuery('.mat-tab-body, .sidenav-info .cdk-focus-trap-content').mCustomScrollbar({ theme: 'dark-thin' });
- this._sidenav.onOpenStart.subscribe(() => this._infoSidenav.close());
- this._sidenav.onOpenStart.subscribe(() => this._doc.body.classList.add('sidenav-open'));
- this._sidenav.onCloseStart.subscribe(() => this._doc.body.classList.remove('sidenav-open'));
- this._infoSidenav.onOpenStart.subscribe(() => this._doc.body.classList.add('sidenav-open'));
- this._infoSidenav.onCloseStart.subscribe(() => this._doc.body.classList.remove('sidenav-open'));
- this._sidenav.onOpenStart.subscribe(() => {
- this.baseLayerSwitcherVisible = false;
- });
- // this._infoSidenav.onOpenStart.subscribe(() => this._sidenav.close());
- this._infoSidenav.onClose.subscribe(() => {
- this.measureInfo = undefined;
- this.layersInfos$ = undefined;
- });
- this._ol3Map.map.updateSize(); // http://gis.stackexchange.com/questions/124326/openlayers-dynamic-viewport-width-and-height-assignment
- this._ol3Map.map.on('click', () => {
- this.baseLayerSwitcherVisible = false;
- });
- this._ol3Map.map.on('moveend', () => {
- let format = new ol.format.WKT(),
- extent = this._ol3Map.map.getView().calculateExtent(this._ol3Map.map.getSize()),
- wkt = format.writeGeometry(ol.geom.Polygon.fromExtent(extent));
- let requestBody = {
- sessionId: '12345abcd',
- clientToken: 'aceeb1c1-b378-439e-821a-843abcabaafc',
- params: {
- bbox: wkt,
- orgId: 1
- }
- };
- this._http.post2('http://192.168.157.38:3000/proxy/tbilisimap-core/api/managelayersws/getLrUserObjsImgs', requestBody)
- .toPromise().then(response => {
- if (response.success) {
- // objVal
- // LayersController/downloadPicture.do?fileId={0}
- }
- });
- });
- this.baseLayerNodes$.then(nodes => {
- let flattenNodes = this._flatten(nodes);
- flattenNodes.sort((a, b) => a.order - b.order)
- .forEach(node => {
- if (node.url) {
- this.layers[node.id] = new ol.layer.Tile({
- visible: node.isSelected,
- source: new ol.source.OSM({
- url: node.url.replace(/\$(\{[xyz]\})/g, '$1'),
- maxZoom: node.params.numZoomLevels,
- crossOrigin: null
- })
- });
- if (node.isSelected) {
- this.baseLayer = this.layers[node.id];
- }
- this._ol3Map.map.addLayer(this.layers[node.id]);
- };
- });
- })
- this.overlayLayerNodes$.then(nodes => {
- let flattenNodes = this._flatten(nodes);
- let extendedSearchPromises = flattenNodes.filter(node => node.extendedSearch)
- .map(node => new Promise(resolve => {
- let requestBody = {
- sessionId: '12345abcd',
- clientToken: 'aceeb1c1-b378-439e-821a-843abcabaafc',
- params: {
- orgId: 1,
- useType: 7,
- lrId: node.id
- }
- };
- this._http.post2('http://192.168.157.38:3000/proxy/tbilisimap-core/api/managelayersws/getLayerTableColumnsConfig', requestBody)
- .toPromise().then(response => {
- let columnsConfigPromises = response.data.map(value => {
- if (value.dataType === 61) {
- let requestBody = {
- sessionId: '12345abcd',
- clientToken: 'aceeb1c1-b378-439e-821a-843abcabaafc',
- params: {
- orgId: 1,
- libId: value.libType
- }
- };
- return this._http.post2('http://192.168.157.38:3000/proxy/tbilisimap-core/api/appws/getLibObjects', requestBody)
- .toPromise().then(response => Object.assign({ libObjects: response.data }, value));
- } else {
- return new Promise(resolve => resolve(value));
- }
- });
- Promise.all(columnsConfigPromises).then(columnsConfig => {
- resolve({ id: node.id, name: node.name, columnsConfig });
- });
- });
- }));
- this.extendedSearch$ = Promise.all(extendedSearchPromises);
- this.extendedSearch$.then((results: any[]) => {
- results.forEach(result => {
- this.extendedSearchModel[result.id] = {};
- result.columnsConfig.filter(config => config.configId).forEach(config => {
- Object.assign(this.extendedSearchModel[result.id], {
- [config.configId]: Object.assign({}, config)
- });
- });
- });
- });
- flattenNodes.sort((a, b) => a.name > b.name ? 1 : (a.name < b.name ? -1 : 0))
- .forEach(node => this.options.push(node.name));
- flattenNodes.sort((a, b) => a.order - b.order)
- .forEach(node => {
- this.checkboxes[node.id] = { isChecked: false, isIndeterminate: false };
- if (node.url || node.urls) {
- this.layers[node.id] = new ol.layer.Tile({
- visible: node.options.visibility || false,
- source: new ol.source.TileWMS({
- url: node.url,
- urls: node.urls,
- projection: 'EPSG:3857',
- params: Object.assign({ 'FORMAT': 'image/png' }, node.params)
- })
- });
- this.layers[node.id].set('name', node.name);
- }
- });
- this.filteredOptions = this.myControl.valueChanges
- .startWith(null)
- .map(val => val ? this.filterOptions(val) : this.options.slice());
- });
- }
- private _flatten(nodes: Node[]) {
- let flattenArray: Node[] = [];
- nodes.forEach(node => flattenArray.push(node, ...this._flatten(node.children || [])));
- return flattenArray;
- }
- private _addInteraction(type: ol.geom.GeometryType) {
- this._removeInteraction();
- let source = this._drawingLayer.getSource();
- this._drawingInteraction = new ol.interaction.Draw({ type, source });
- this._ol3Map.map.addInteraction(this._drawingInteraction);
- return this._drawingInteraction;
- }
- private _removeInteraction() {
- if (this._drawingInteraction) {
- this._ol3Map.map.removeInteraction(this._drawingInteraction);
- this._drawingInteraction = null;
- }
- }
- private _addMesaureTool(type: ol.geom.GeometryType, onDrawEnd: Function) {
- const clear = () => {
- this._infoSidenav.close();
- this._drawingLayer.getSource().clear();
- };
- clear();
- let interaction = this._addInteraction(type);
- interaction.on('drawstart', clear);
- interaction.on('drawend', onDrawEnd);
- return interaction;
- }
- private _animateTo(center: ol.Coordinate, zoom: number = 14) {
- this._ol3Map.map.getView().animate({ center, zoom });
- }
- drawWkt(geometryWkt: string) {
- this._drawingLayer.getSource().clear();
- let format = new ol.format.WKT(),
- geometry = format.readGeometry(geometryWkt.replace(/,\)$/g, ')')),
- feature = new ol.Feature({ geometry });
- this._drawingLayer.getSource().addFeature(feature);
- if (geometry.getType() === 'Point') {
- this._animateTo(geometry['getCoordinates'](), 18);
- } else {
- this._ol3Map.map.getView().fit(feature.getGeometry().getExtent(), this._ol3Map.map.getSize());
- }
- }
- search(event) {
- let requestBody = {
- sessionId: "123456abcdefg",
- params: {
- orgId: 1,
- searchText: event.query,
- page: 0,
- size: 20
- }
- };
- this.searchResults$ = this._http.post2('http://192.168.157.38:3000/proxy/tbilisimap-core/api/mapsearchws/search', requestBody)
- .toPromise().then(response => response.data || []);
- }
- extendedSearch(event: Event, layer: Node) {
- event.stopPropagation();
- this.tabGroupSelectedIndex = 3;
- this._extendedSearchAccordion.tabs.forEach(tab => {
- tab.selected = false;
- });
- setTimeout(() => {
- this._extendedSearchAccordion.tabs.forEach(tab => {
- if (tab.header === layer.name) {
- tab.selected = true;
- } else {
- tab.selected = false;
- }
- });
- }, 400);
- }
- doExtendedSearch(
- layerId: number,
- recordsFrom: number = 1,
- recordsTo: number = 10
- ) {
- const snake2Camel = (value: string) => value.toLowerCase().replace(/_\w/g, (m: string) => m[1].toUpperCase()),
- transformFn = value => field => {
- let obj = Object.assign({ columnValue: value[snake2Camel(field.columnName)] }, field);
- if (field.dataType === 61) {
- let libObject = field.libObjects.find(o => o.objId === obj.columnValue);
- if (libObject) {
- Object.assign(obj, { columnValue: libObject.objId });
- }
- }
- return obj;
- };
- if (this.extendedSearchModel[layerId]) {
- let fields = Object.keys(this.extendedSearchModel[layerId])
- .map(key => this.extendedSearchModel[layerId][key])
- .sort((a, b) => a.configOrder - b.configOrder);
- let fieldWithValueList = fields.filter(field => field.fieldValue)
- .map(field => ({ fieldName: field.columnName, fieldType: field.dbDataType, fieldValue: field.fieldValue }));
- let requestBody = {
- sessionId: '12345abcd',
- clientToken: 'aceeb1c1-b378-439e-821a-843abcabaafc',
- params: {
- orgId: 1,
- lrId: layerId,
- fieldWithValueList,
- recordsFrom,
- recordsTo
- }
- };
- this.extendedSearchResult$ = this._http.post2('http://192.168.157.38:3000/proxy/tbilisimap-core/api/mapsearchws/searchLr', requestBody)
- .toPromise().then(response => response.data.map(value => fields.map(transformFn(value))));
- }
- }
- clearExtendedSearchModel(layerId: number) {
- if (this.extendedSearchModel[layerId]) {
- Object.keys(this.extendedSearchModel[layerId]).forEach(configId => {
- delete this.extendedSearchModel[layerId][configId].fieldValue;
- });
- }
- }
- toggleBaseLayerSwitcherVisibility() {
- this.baseLayerSwitcherVisible = !this.baseLayerSwitcherVisible;
- }
- onSelectSearch(event) {
- this._sidenav.close().then(() => {
- this.drawWkt(event.geometryWkt);
- });
- }
- onClickCheckbox(event: Event) {
- event.stopPropagation();
- }
- setBaseLayer(node: Node) {
- if (this.baseLayer) {
- this.baseLayer.setVisible(false);
- }
- this.baseLayer = this.layers[node.id];
- this.baseLayer.setVisible(true);
- }
- onChangeCheckbox(node: TreeNode) {
- const setChecked = (node: TreeNode, isChecked: boolean) => {
- this.checkboxes[node.id].isChecked = isChecked;
- this.checkboxes[node.id].isIndeterminate = false;
- if (this.layers[node.id]) {
- if (isChecked) {
- this._ol3Map.map.addLayer(this.layers[node.id]);
- } else {
- this._ol3Map.map.removeLayer(this.layers[node.id]);
- }
- this.layers[node.id].setVisible(isChecked);
- }
- let children = node.children || [];
- children.forEach(child => setChecked(child, isChecked));
- };
- setChecked(node, !this.checkboxes[node.id].isChecked);
- let parent = node;
- while (!parent.isRoot) {
- parent = parent.parent;
- let checked = parent.children.filter(child => this.checkboxes[child.id].isChecked),
- indeterminate = parent.children.filter(child => this.checkboxes[child.id].isIndeterminate);
- let isParentChecked = false,
- isParentIndeterminate = false;
- if (checked.length === parent.children.length) {
- isParentChecked = true;
- } else if (checked.length > 0 || indeterminate.length > 0) {
- isParentIndeterminate = true;
- }
- this.checkboxes[parent.id].isChecked = isParentChecked;
- this.checkboxes[parent.id].isIndeterminate = isParentIndeterminate;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment