init push

This commit is contained in:
Fabian Jeglinski
2019-04-28 13:36:05 +02:00
parent cf3ce512bd
commit 258cc9abb6
38 changed files with 15168 additions and 36 deletions
@@ -0,0 +1,35 @@
<form #uploadForm="ngForm" (ngSubmit)="onSubmit()">
<h1 mat-dialog-title>Layer {{ editMode ? 'bearbeiten' : 'hinzufügen' }}</h1>
<div mat-dialog-content>
<div class="custom-control mat-typography">
<p>Geojson *</p>
<input type="file" placeholder="Layername" (change)="onFileChoose($event.target.files)">
<div class="error-box">
<small *ngIf="!formData.layerData && uploadIsDirty" class="mat-error">Bitte laden Sie eine Geojson Datei hoch
</small>
<small *ngIf="uploadError" class="mat-error">Bitte wählen Sie ausschließlich ein Datei vom Typ json</small>
</div>
</div>
<mat-form-field>
<input [(ngModel)]="formData.layerName" #layerName="ngModel" name="layerName" matInput placeholder="Layername"
required>
<mat-error *ngIf="layerName.hasError('required') && layerName.dirty">
Please enter a valid email address
</mat-error>
</mat-form-field>
<div class="custom-control mat-typography">
<p>Layer color</p>
<input type="color" matInput [(ngModel)]="formData.color" name="color">
</div>
</div>
<div mat-dialog-actions>
<button mat-button type="button" (click)="close()">Abbrechen</button>
<button mat-button cdkFocusInitial [disabled]="uploadForm.invalid || !formData.layerData || uploadError">
{{ editMode ? 'Speichern' : 'Hinzufügen' }}
</button>
</div>
</form>
@@ -0,0 +1,3 @@
.custom-control{
margin-bottom: 1rem;
}
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AddLayerComponent } from './add-layer.component';
describe('AddLayerComponentComponent', () => {
let component: AddLayerComponent;
let fixture: ComponentFixture<AddLayerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AddLayerComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AddLayerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,81 @@
import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
import {ValidationErrors} from "@angular/forms";
import {RawLayer} from "../models/RawLayer";
import {Utils} from "../misc/Utils";
/**
* TODO: Add description
*
* TODO:
* - Improve styling
* - improve error handling (button disabled from the beginning)
* - improve validation - using validationErrors as type is not necessary
* - improve file handling ( especially in edit mode)
*/
@Component({
selector: 'app-add-layer',
templateUrl: './add-layer.component.html',
styleUrls: ['./add-layer.component.scss']
})
export class AddLayerComponent {
public formData = {
layerName: '',
layerData: null,
color: '#4fadc2'
}
public uploadError: ValidationErrors = null;
public uploadIsDirty: boolean = false;
public editMode : boolean = false;
constructor(
public dialogRef: MatDialogRef<AddLayerComponent>,
@Inject(MAT_DIALOG_DATA) public data: RawLayer) {
// set rawLayer data
if (data) {
this.formData.layerName = data.name;
this.formData.layerData = data.data;
this.formData.color = Utils.rgbToHex(data.color[0],data.color[1],data.color[2]);
this.editMode = true;
}
}
onFileChoose(files: File[]) {
this.uploadIsDirty = true;
const file = files[0];
if (!file) {
this.formData.layerData = null;
return;
}
const fileParts = file.name.split('.');
// set file name as layer name if no name exists
if (!this.formData.layerName) {
this.formData.layerName = fileParts[0];
}
const fileExtension = fileParts.pop();
if (file.type === 'application/json' || ['geojson', 'json'].includes(fileExtension)) {
this.uploadError = null;
} else {
this.uploadError = {
invalidFileType: true
}
}
const fileReader = new FileReader();
fileReader.onload = () => this.formData.layerData = fileReader.result;
fileReader.readAsText(files[0]);
}
close(data?: any): void {
this.dialogRef.close(data);
}
onSubmit() {
const rawLayer = new RawLayer(this.formData.layerName, this.formData.layerData, Utils.hexToRgba(this.formData.color));
this.close(rawLayer);
}
}
+7 -1
View File
@@ -1,7 +1,13 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {MapComponent} from "./map/map.component";
import {LeafletMapComponent} from "./leaflet-map/leaflet-map.component";
const routes: Routes = [];
const routes: Routes = [
{path: '**', component: MapComponent},
{path: 'osm', component: MapComponent},
{path: 'leaflet', component: LeafletMapComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
-20
View File
@@ -1,21 +1 @@
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
<li>
<h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
</li>
<li>
<h2><a target="_blank" rel="noopener" href="https://angular.io/cli">CLI Documentation</a></h2>
</li>
<li>
<h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
</li>
</ul>
<router-outlet></router-outlet>
+3 -2
View File
@@ -1,4 +1,5 @@
import { Component } from '@angular/core';
import {Component} from '@angular/core';
import 'hammerjs';
@Component({
selector: 'app-root',
@@ -6,5 +7,5 @@ import { Component } from '@angular/core';
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'gane-web';
}
+25 -3
View File
@@ -3,16 +3,38 @@ import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MapComponent } from './map/map.component';
import { LeafletMapComponent } from './leaflet-map/leaflet-map.component';
import {HttpClient, HttpClientModule} from "@angular/common/http";
import {FormsModule} from "@angular/forms";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {MatCardModule, MatDialogModule, MatGridListModule, MatInputModule, MatToolbarModule} from "@angular/material";
import {DragDropModule} from "@angular/cdk/drag-drop";
import { AddLayerComponent } from './add-layer-component/add-layer.component';
@NgModule({
declarations: [
AppComponent
AppComponent,
MapComponent,
LeafletMapComponent,
AddLayerComponent
],
imports: [
BrowserModule,
AppRoutingModule
BrowserAnimationsModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
MatCardModule,
MatGridListModule,
MatToolbarModule,
DragDropModule,
MatInputModule,
MatDialogModule,
],
entryComponents: [
AddLayerComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
+15
View File
@@ -0,0 +1,15 @@
/**
* Enum that contains the projections types
*/
export enum EPSG {
/**
* Default open layers projection
* WGS 84 / Pseudo-Mercator -- Spherical Mercator, Google Maps, OpenStreetMap, Bing, ArcGIS, ESRI
*/
openLayersDefault = 'EPSG:3857',
/**
* GPS coordinate system -> latitude/longitude
* WGS 84 -- WGS84 - World Geodetic System 1984, used in GPS
*/
wgs84 = 'EPSG:4326'
}
@@ -0,0 +1 @@
<div id="mapid"></div>
@@ -0,0 +1 @@
#mapid { height: 50vh; }
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LeafletMapComponent } from './leaflet-map.component';
describe('LeafletMapComponent', () => {
let component: LeafletMapComponent;
let fixture: ComponentFixture<LeafletMapComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LeafletMapComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LeafletMapComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,52 @@
import {Component, OnInit} from '@angular/core';
import * as L from 'Leaflet';
import {HttpClient} from "@angular/common/http";
import {GeoJSON} from "Leaflet";
import {GeoJsonObject} from "geojson";
@Component({
selector: 'app-leaflet-map',
templateUrl: './leaflet-map.component.html',
styleUrls: ['./leaflet-map.component.scss']
})
export class LeafletMapComponent implements OnInit {
private map;
private vectorLayerFiles: string[] = [
'./assets/geolayer/flurstuecke-nutzer-baum-kompensation.geojson',
// './assets/geolayer/bebauung.geojson',
'./assets/geolayer/feldwege.geojson',
'./assets/geolayer/gehoelze.geojson',
'./assets/geolayer/gewaesser.geojson',
// './assets/geolayer/grabensysteme.geojson',
// './assets/geolayer/grabenuebergaenge.geojson',
// './assets/geolayer/gsp_einsatzgebiete.geojson',
// './assets/geolayer/stromleitungen.geojson',
// './assets/geolayer/strommasten.geojson',
// './assets/geolayer/windenergieanlagen.geojson',
];
constructor(private http: HttpClient) {
}
async ngOnInit() {
this.map = L.map('mapid').setView([53.1582, 8.7728], 13);
// L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
// attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
// }).addTo(this.map);
// L.marker([53.1582, 8.7728]).addTo(this.map)
// .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
// .openPopup();
const layers : any[] = await this.getGeoJsons();
layers.forEach(layer => L.geoJSON(layer).addTo(this.map));
}
async getGeoJsons() {
const promises = this.vectorLayerFiles.map(file => this.http.get(file).toPromise());
return await Promise.all(promises);
}
}
+64
View File
@@ -0,0 +1,64 @@
<div class="content">
<!-- map area -->
<div class="map-area">
<div class="map" #mapContainer></div>
<div class="map-info">
<form>
<label>
Show OSM Map
<input type="checkbox" [checked]="baseLayer.getVisible()"
(click)="baseLayer.setVisible(!baseLayer.getVisible())">
</label>
</form>
<div>
{{ cursorCoordinates ? cursorCoordinates : 'Lat: ? / Long: ?' }}
</div>
</div>
</div>
<!-- layer property area-->
<div class="layer-property-area">
<mat-card>
<mat-card-header>
<mat-card-title>Layer Properties</mat-card-title>
</mat-card-header>
<mat-card-content>
<div>
{{ currentFeatureInfo | json}}
</div>
</mat-card-content>
</mat-card>
</div>
<!-- layer control area-->
<div class="layer-control-area">
<mat-card>
<mat-card-header>
<mat-card-title>Layer</mat-card-title>
<div class="controls">
<i class="material-icons" (click)="addLayer()">add_circle</i>
</div>
</mat-card-header>
<mat-card-content>
<div cdkDropList class="layer-list" (cdkDropListDropped)="drop($event)">
<div class="list-entry" *ngFor="let layer of customLayerCollection.getArray();let i = index" cdkDrag>
<h4>{{layer.get('name') }}</h4>
<i class="material-icons" (click)="centerLayerOnMap(layer)">
center_focus_strong
</i>
<i class="material-icons" (click)="toggleLayerVisibility(layer)">
{{layer.getVisible() ? 'visibility' : 'visibility_off'}}
</i>
<i class="material-icons" (click)="editLayer(i)">
edit
</i>
<i class="material-icons" (click)="deleteLayer(layer)">
delete
</i>
</div>
</div>
</mat-card-content>
<mat-card-actions>
<button mat-button (click)="saveLayers()">Speichern</button>
</mat-card-actions>
</mat-card>
</div>
</div>
+94
View File
@@ -0,0 +1,94 @@
.content {
padding: 2rem;
display: grid;
grid-template-columns: 2fr 1fr 1fr;
grid-template-rows: auto;
&,
& * {
box-sizing: border-box;
}
.map-area {
position: relative;
width: 100%;
height: 100%;
.map {
width: 100%;
height: 80vh; // TODO make canvas resizable ..
}
.map-info {
position: absolute;
bottom: 0;
left: 0;
background-color: white;
display: flex;
justify-content: flex-start;
width: 100%;
padding: 6px;
*:not(:first-child) {
margin-left: 12px;
}
}
}
.layer-control-area {
.layer-list {
max-width: 100%;
border: solid 1px #ccc;
min-height: 60px;
display: block;
background: white;
border-radius: 4px;
overflow: hidden;
.list-entry {
padding: 20px 10px;
border-bottom: solid 1px #ccc;
color: rgba(0, 0, 0, 0.87);
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
cursor: move;
background: white;
font-size: 14px;
&:last-child {
border: none;
}
}
}
.layer-list.cdk-drop-list-dragging .list-entry:not(.cdk-drag-placeholder) {
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
}
}
.cdk-drag-preview {
box-sizing: border-box;
border-radius: 4px;
box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
0 8px 10px 1px rgba(0, 0, 0, 0.14),
0 3px 14px 2px rgba(0, 0, 0, 0.12);
}
.cdk-drag-placeholder {
opacity: 0;
}
.cdk-drag-animating {
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
+25
View File
@@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MapComponent } from './map.component';
describe('MapComponent', () => {
let component: MapComponent;
let fixture: ComponentFixture<MapComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MapComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MapComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
+252
View File
@@ -0,0 +1,252 @@
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import {fromLonLat, transform} from 'ol/proj';
import VectorLayer from 'ol/layer/Vector';
import {OSM} from 'ol/source';
import {CdkDragDrop} from "@angular/cdk/drag-drop";
import {MatDialog} from "@angular/material";
import {AddLayerComponent} from "../add-layer-component/add-layer.component";
import {RawLayer} from "../models/RawLayer";
import LayerGroup from 'ol/layer/Group';
import {Collection} from "openlayers";
import {EPSG} from "../enums/EPSG";
import {inAndOut} from 'ol/easing';
/**
* TODO: add description
*/
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit {
@ViewChild('mapContainer') mapContainer: ElementRef<HTMLDivElement>;
public map: Map;
public baseLayer: TileLayer;
/**
* Represents the custom layer that were uploaded by user
*/
private customLayerGroup: LayerGroup;
/**
* Returns the layer collection of the customLayerGroup
*/
get customLayerCollection(): Collection<VectorLayer> {
return this.customLayerGroup.getLayers();
}
/**
* The coordinates in wgs84 according to the cursor position
*/
public cursorCoordinates: string;
/**
* The properties of the current feature. The current layer is the layer beneath the cursor.
*/
public currentFeatureInfo: any;
constructor(public dialog: MatDialog) {
}
ngOnInit() {
this.initBaseLayer();
this.initLayerGroup();
this.initMap();
}
/**
* Inits the base layer (OSM TileLayer)
*/
initBaseLayer() {
this.baseLayer = new TileLayer({
source: new OSM()
});
}
/**
* Inits the customLayerGroup
*/
initLayerGroup() {
this.customLayerGroup = new LayerGroup({
layers: []
});
}
/**
* Inits the open layers map instance
*/
private initMap() {
this.map = new Map({
target: this.mapContainer.nativeElement,
layers: [
this.baseLayer,
this.customLayerGroup
],
view: new View({
center: fromLonLat([0, 0]),
zoom: 2
})
});
this.addMapEventlistener();
// without this line the map is only visible after resizing window
requestAnimationFrame(() => {
this.map.updateSize();
})
}
/**
* Adds all map event listener
*/
private addMapEventlistener() {
// get current cursor coordinates to transform and display them
this.map.on('pointermove', (evt) => {
const tmpCoords = transform(evt.coordinate, EPSG.openLayersDefault, EPSG.wgs84);
this.cursorCoordinates = `Lat: ${tmpCoords[1]} / Long: ${tmpCoords[0]}`;
});
// add event to get feature infos
this.map.on('pointermove', (evt) => {
if (evt.dragging) {
return;
}
const pixel = this.map.getEventPixel(evt.originalEvent);
this.displayFeatureInfo(pixel);
});
}
/**
* Gets all feature infos for each feature at the given pixel.
* @param pixel
*/
private displayFeatureInfo(pixel) {
const features = [];
this.map.forEachFeatureAtPixel(pixel, (feature) => {
features.push(feature)
}
);
if (features.length == 0) {
this.currentFeatureInfo = 'Too many features. Please zoom in to see feature infos';
} else if (features.length == 1) {
features.forEach(feature => {
const properties = feature.getProperties();
delete properties.geometry;
this.currentFeatureInfo = properties;
})
} else {
this.currentFeatureInfo = null;
}
};
// private colorPolygons(feature: Feature, resolution: any) {
// const styles = {
// black: new Style({
// stroke: new Stroke({
// color: '#86665a',
// width: 1
// }),
// fill: new Fill({
// color: 'rgba(121,85,72, 0.4)',
// })
// }),
// green: new Style({
// stroke: new Stroke({
// color: '#b8c633',
// width: 1
// }),
// fill: new Fill({
// color: 'rgba(205,220,57,0.4)',
// })
// })
// }
// // console.log(feature.getProperties()['Grünland'],feature.getProperties());
// if (feature.getProperties()['Nutzung'] === 'Grünland') {
// return styles.green;
// } else {
// return styles.black;
// }
// }
/**
* Opens a dialog to create a new custom layer
*/
addLayer(): void {
const dialogRef = this.dialog.open(AddLayerComponent);
dialogRef.afterClosed().subscribe(rawLayer => {
if (rawLayer) {
const customLayer = RawLayer.toVectorLayer(rawLayer);
this.centerLayerOnMap(customLayer);
this.customLayerCollection.push(customLayer);
}
}
);
}
/**
* Opens a dialog to edit a custom layer
*/
editLayer(index: number): void {
const vectorLayer = this.customLayerCollection.item(index);
const rawLayer = RawLayer.fromVectorLayer(vectorLayer);
const dialogRef = this.dialog.open(AddLayerComponent, {data: rawLayer});
dialogRef.afterClosed().subscribe(rawLayer => {
if (rawLayer) {
// TODO
// when a layer was edited the information about the file is lost.
// That causes that the layer is removed from map. In such a case, just edit color or name.
const customLayer = RawLayer.toVectorLayer(rawLayer);
this.customLayerCollection.setAt(index, customLayer);
}
}
);
}
/**
* Updates the customLayer collection according to drag and drop actions.
* @param event
*/
drop(event: CdkDragDrop<RawLayer[]>) {
const tmp = this.customLayerCollection.item(event.previousIndex);
this.customLayerCollection.removeAt(event.previousIndex);
this.customLayerCollection.insertAt(event.currentIndex, tmp);
}
deleteLayer(layer: VectorLayer) {
this.customLayerCollection.remove(layer);
}
/**
* Toggles the visibility of a custom layer
* @param index
*/
toggleLayerVisibility(layer: VectorLayer) {
layer.setVisible(!layer.getVisible());
}
saveLayers(): RawLayer[] {
const rawLayers = [];
this.customLayerCollection.forEach(layer => rawLayers.push(RawLayer.fromVectorLayer(layer)));
return rawLayers;
}
/**
* Focusses the passed layer on map
* @param customLayer
*/
private centerLayerOnMap(customLayer: VectorLayer) {
const options = {
size: this.map.getSize(),
duration: 888,
easing: inAndOut
}
this.map.getView().fit(customLayer.getSource().getExtent(), options);
}
}
+3
View File
@@ -0,0 +1,3 @@
export class Config{
static readonly GEO_JSON_PREFIX: string = 'GANE';
}
+28
View File
@@ -0,0 +1,28 @@
export class Utils {
/**
* Converts rgb values to a hex string
* @param r
* @param g
* @param b
*/
public static rgbToHex(r: number, g: number, b: number): string {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
/**
* Converts a hex string and a opacity value to rgba array representation like
* #ffffff u. 0.5 -> [255,255,255,0.5]
* @param hex
* @param opacity
*/
public static hexToRgba(hex: string, opacity: number = 1): number[] {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? [
parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16),
opacity
] : null;
}
}
+106
View File
@@ -0,0 +1,106 @@
import VectorLayer from 'ol/layer/Vector';
import GeoJSON from 'ol/format/GeoJSON';
import {Vector as VectorSource} from 'ol/source';
import {EPSG} from "../enums/EPSG";
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';
import {Config} from "../misc/Config";
/**
* Represents a raw (not processed) map layer
*/
export class RawLayer {
constructor(
/**
* Name of layer
*/
public name: string,
/**
* Data of Layer (normally in geojson format)
*/
public data: string,
/**
* Layer stroke color as number array with opacity like -> [255, 255, 255, 0.5]
* The fill color is an opaque decreased derivation of this value.
*/
public color: number[]
) {
this.saveColorToGeoJSON();
}
/**
* Creates a RawLayer instance from a VectorLayer and saves the style properties in geojson. Consider that the
* layer color information are applied to each feature!
* @param layer
*/
public static fromVectorLayer(layer: VectorLayer): RawLayer {
const writer = new GeoJSON();
const source = layer.getSource();
// get default style values
const features = source.getFeatures();
const featureProperties = features[0].getProperties();
const rawLayerColor = featureProperties[Config.GEO_JSON_PREFIX]['default-style-stroke'];
const geoJSONString = writer.writeFeatures(features,{featureProjection: EPSG.openLayersDefault});
return new RawLayer(layer.get('name'), geoJSONString, rawLayerColor);
}
/**
* Creates a VectorLayer instance from a RawLayer and applies the layer color to all features
* @param rawLayer
*/
public static toVectorLayer(rawLayer: RawLayer): VectorLayer {
const vectorSource = new VectorSource();
const geoJSON = new GeoJSON();
// load geoJSON features from rawLayer
const features = geoJSON.readFeatures(rawLayer.data, {featureProjection: EPSG.openLayersDefault});
// apply style to all features
features.forEach(feature => {
// TODO
// determine if this feature has a own color! If so, do not apply default color and use own color.
const featureProperties = feature.getProperties();
const strokeColor = featureProperties[Config.GEO_JSON_PREFIX]['default-style-stroke'];
const fillColor = featureProperties[Config.GEO_JSON_PREFIX]['default-style-fill'];
feature.setStyle(new Style({
stroke: new Stroke({
color: strokeColor,
width: 1
}),
fill: new Fill({
color: fillColor
})
}));
})
// add features to source
vectorSource.addFeatures(features);
return new VectorLayer({
name: rawLayer.name,
renderMode: 'image',
source: vectorSource
});
}
/**
* Adds the RawLayer color property to all feature properties from data attribute
*/
private saveColorToGeoJSON() {
const geoJSON = new GeoJSON();
// load geoJSON features from rawLayer
const features = geoJSON.readFeatures(this.data, {featureProjection: EPSG.openLayersDefault});
features.forEach(feature => {
// save default color in feature properties
const stylesToSave = {};
stylesToSave[Config.GEO_JSON_PREFIX] = {};
stylesToSave[Config.GEO_JSON_PREFIX]['default-style-stroke'] = this.color;
stylesToSave[Config.GEO_JSON_PREFIX]['default-style-fill'] = [...this.color.slice(0, 3), 0.1];
feature.setProperties(stylesToSave);
})
this.data = geoJSON.writeFeatures(features, {featureProjection: EPSG.openLayersDefault});
}
}