-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathOlStyleParser.ts
1533 lines (1432 loc) · 53.3 KB
/
OlStyleParser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { parseFont } from 'css-font-parser';
import {
CapType,
FillSymbolizer,
Filter,
IconSymbolizer,
JoinType,
LineSymbolizer,
MarkSymbolizer,
Operator,
PointSymbolizer,
ReadStyleResult,
Rule,
Style,
StyleParser,
StyleType,
Symbolizer,
TextSymbolizer,
UnsupportedProperties,
WriteStyleResult
} from 'geostyler-style/dist/style';
import {
isGeoStylerBooleanFunction,
isGeoStylerFunction,
isGeoStylerStringFunction,
isIconSymbolizer,
isMarkSymbolizer,
isSprite
} from 'geostyler-style/dist/typeguards';
import OlImageState from 'ol/ImageState';
import OlGeomPoint from 'ol/geom/Point';
import OlStyle, { StyleFunction as OlStyleFunction, StyleLike as OlStyleLike} from 'ol/style/Style';
import OlStyleImage from 'ol/style/Image';
import OlStyleStroke from 'ol/style/Stroke';
import OlStyleText, { Options as OlStyleTextOptions } from 'ol/style/Text';
import OlStyleCircle, { Options as OlStyleCircleOptions } from 'ol/style/Circle';
import OlStyleFill from 'ol/style/Fill';
import OlStyleIcon, { Options as OlStyleIconOptions } from 'ol/style/Icon';
import OlStyleRegularshape from 'ol/style/RegularShape';
import { METERS_PER_UNIT } from 'ol/proj/Units';
import OlStyleUtil from './Util/OlStyleUtil';
import { toContext } from 'ol/render';
import OlFeature from 'ol/Feature';
export interface OlParserStyleFct {
(feature?: any, resolution?: number): any;
__geoStylerStyle: Style;
}
type SymbolizerKeyType = keyof UnsupportedProperties['Symbolizer'];
/**
* This parser can be used with the GeoStyler.
* It implements the GeoStyler-Style Parser interface to work with OpenLayers styles.
*
* @class OlStyleParser
* @implements StyleParser
*/
export class OlStyleParser implements StyleParser<OlStyleLike> {
/**
* The name of the OlStyleParser.
*/
public static title = 'OpenLayers Style Parser';
unsupportedProperties: UnsupportedProperties = {
Symbolizer: {
MarkSymbolizer: {
avoidEdges: 'none',
blur: 'none',
offsetAnchor: 'none',
pitchAlignment: 'none',
pitchScale: 'none'
},
FillSymbolizer: {
antialias: 'none',
opacity: {
support: 'none',
info: 'Use fillOpacity instead.'
}
},
IconSymbolizer: {
allowOverlap: 'none',
anchor: 'none',
avoidEdges: 'none',
color: 'none',
haloBlur: 'none',
haloColor: 'none',
haloWidth: 'none',
keepUpright: 'none',
offsetAnchor: 'none',
size: {
support: 'partial',
info: 'Will set/get the width of the ol Icon.'
},
optional: 'none',
padding: 'none',
pitchAlignment: 'none',
rotationAlignment: 'none',
textFit: 'none',
textFitPadding: 'none'
},
LineSymbolizer: {
blur: 'none',
gapWidth: 'none',
gradient: 'none',
miterLimit: 'none',
roundLimit: 'none',
spacing: 'none',
graphicFill: 'none',
graphicStroke: 'none',
perpendicularOffset: 'none'
},
RasterSymbolizer: 'none',
TextSymbolizer: {
anchor: 'none',
placement: {
support:'partial',
info: 'point and line supported. line-center will be mapped to line.'
}
}
},
Function: {
double2bool: {
support: 'none',
info: 'Always returns false'
},
atan2: {
support: 'none',
info: 'Currently returns the first argument'
},
rint: {
support: 'none',
info: 'Currently returns the first argument'
},
numberFormat: {
support: 'none',
info: 'Currently returns the first argument'
},
strAbbreviate: {
support: 'none',
info: 'Currently returns the first argument'
}
}
};
title = 'OpenLayers Style Parser';
olIconStyleCache: any = {};
OlStyleConstructor = OlStyle;
OlStyleImageConstructor = OlStyleImage;
OlStyleFillConstructor = OlStyleFill;
OlStyleStrokeConstructor = OlStyleStroke;
OlStyleTextConstructor = OlStyleText;
OlStyleCircleConstructor = OlStyleCircle;
OlStyleIconConstructor = OlStyleIcon;
OlStyleRegularshapeConstructor = OlStyleRegularshape;
constructor(ol?: any) {
if (ol) {
this.OlStyleConstructor = ol.style.Style;
this.OlStyleImageConstructor = ol.style.Image;
this.OlStyleFillConstructor = ol.style.Fill;
this.OlStyleStrokeConstructor = ol.style.Stroke;
this.OlStyleTextConstructor = ol.style.Text;
this.OlStyleCircleConstructor = ol.style.Circle;
this.OlStyleIconConstructor = ol.style.Icon;
this.OlStyleRegularshapeConstructor = ol.style.RegularShape;
}
}
isOlParserStyleFct = (x: any): x is OlParserStyleFct => {
return typeof x === 'function';
};
/**
* Get the GeoStyler-Style PointSymbolizer from an OpenLayers Style object.
*
* @param olStyle The OpenLayers Style object
* @return The GeoStyler-Style PointSymbolizer
*/
getPointSymbolizerFromOlStyle(olStyle: OlStyle): PointSymbolizer {
let pointSymbolizer: PointSymbolizer;
if (olStyle.getImage() instanceof this.OlStyleCircleConstructor) {
// circle
const olCircleStyle: OlStyleCircle = olStyle.getImage() as OlStyleCircle;
const olFillStyle = olCircleStyle.getFill();
const olStrokeStyle = olCircleStyle.getStroke();
const offset = olCircleStyle.getDisplacement() as [number, number];
const circleSymbolizer: MarkSymbolizer = {
kind: 'Mark',
wellKnownName: 'circle',
color: olFillStyle ? OlStyleUtil.getHexColor(olFillStyle.getColor() as string) : undefined,
opacity: olCircleStyle.getOpacity() !== 1 ? olCircleStyle.getOpacity() : undefined,
fillOpacity: olFillStyle ? OlStyleUtil.getOpacity(olFillStyle.getColor() as string) : undefined,
radius: (olCircleStyle.getRadius() !== 0) ? olCircleStyle.getRadius() : 5,
strokeColor: olStrokeStyle ? olStrokeStyle.getColor() as string : undefined,
strokeOpacity: olStrokeStyle ? OlStyleUtil.getOpacity(olStrokeStyle.getColor() as string) : undefined,
strokeWidth: olStrokeStyle ? olStrokeStyle.getWidth() : undefined,
offset: offset[0] || offset[1] ? offset : undefined
};
pointSymbolizer = circleSymbolizer;
} else if (olStyle.getImage() instanceof this.OlStyleRegularshapeConstructor) {
// square, triangle, star, cross or x
const olRegularStyle: OlStyleRegularshape = olStyle.getImage() as OlStyleRegularshape;
const olFillStyle = olRegularStyle.getFill();
const olStrokeStyle = olRegularStyle.getStroke();
const radius = olRegularStyle.getRadius();
const radius2 = olRegularStyle.getRadius2();
const points = olRegularStyle.getPoints();
const angle = olRegularStyle.getAngle();
const offset = olRegularStyle.getDisplacement() as [number, number];
const markSymbolizer: MarkSymbolizer = {
kind: 'Mark',
color: olFillStyle ? OlStyleUtil.getHexColor(olFillStyle.getColor() as string) : undefined,
opacity: olRegularStyle.getOpacity() !== 1 ? olRegularStyle.getOpacity() : undefined,
fillOpacity: olFillStyle ? OlStyleUtil.getOpacity(olFillStyle.getColor() as string) : undefined,
strokeColor: olStrokeStyle ? olStrokeStyle.getColor() as string : undefined,
strokeOpacity: olStrokeStyle ? OlStyleUtil.getOpacity(olStrokeStyle.getColor() as string) : undefined,
strokeWidth: olStrokeStyle ? olStrokeStyle.getWidth() : undefined,
radius: (radius !== 0) ? radius : 5,
// Rotation in openlayers is radians while we use degree
rotate: olRegularStyle.getRotation() / Math.PI * 180,
offset: offset[0] || offset[1] ? offset : undefined
} as MarkSymbolizer;
switch (points) {
case 2:
switch (angle) {
case 0:
markSymbolizer.wellKnownName = 'shape://vertline';
break;
case Math.PI / 2:
markSymbolizer.wellKnownName = 'shape://horline';
break;
case Math.PI / 4:
markSymbolizer.wellKnownName = 'shape://slash';
break;
case 2 * Math.PI - (Math.PI / 4):
markSymbolizer.wellKnownName = 'shape://backslash';
break;
default:
break;
}
break;
case 3:
switch (angle) {
case 0:
markSymbolizer.wellKnownName = 'triangle';
break;
case Math.PI / 2:
markSymbolizer.wellKnownName = 'shape://carrow';
break;
default:
break;
}
break;
case 4:
if (Number.isFinite(radius2)) {
// cross or x
if (olRegularStyle.getAngle() === 0) {
// cross
markSymbolizer.wellKnownName = 'cross';
} else {
// x
markSymbolizer.wellKnownName = 'x';
}
} else {
// square
markSymbolizer.wellKnownName = 'square';
}
break;
case 5:
// star
markSymbolizer.wellKnownName = 'star';
break;
default:
throw new Error('Could not parse OlStyle. Only 2, 3, 4 or 5 point regular shapes are allowed');
}
pointSymbolizer = markSymbolizer;
} else if (olStyle.getText() instanceof this.OlStyleTextConstructor) {
const olTextStyle: OlStyleText = olStyle.getText() as OlStyleText;
const olFillStyle = olTextStyle.getFill();
const olStrokeStyle = olTextStyle.getStroke();
const rotation = olTextStyle.getRotation();
let char = olTextStyle.getText() || 'a';
const font = olTextStyle.getFont() || '10px sans-serif';
const fontName = OlStyleUtil.getFontNameFromOlFont(font);
const radius = OlStyleUtil.getSizeFromOlFont(font);
const offset = [olTextStyle.getOffsetX(), olTextStyle.getOffsetY()];
if (Array.isArray(char)) {
char = char[0];
}
pointSymbolizer = {
kind: 'Mark',
wellKnownName: `ttf://${fontName}#0x${char.charCodeAt(0).toString(16)}`,
color: olFillStyle ? OlStyleUtil.getHexColor(olFillStyle.getColor() as string) : undefined,
opacity: olFillStyle ? OlStyleUtil.getOpacity(olFillStyle.getColor() as string) : undefined,
strokeColor: olStrokeStyle ? olStrokeStyle.getColor() as string : undefined,
strokeOpacity: olStrokeStyle ? OlStyleUtil.getOpacity(olStrokeStyle.getColor() as string) : undefined,
strokeWidth: olStrokeStyle ? olStrokeStyle.getWidth() : undefined,
radius: (radius !== 0) ? radius : 5,
// Rotation in openlayers is radians while we use degree
rotate: rotation ? rotation / Math.PI * 180 : 0,
offset: offset[0] || offset[1] ? offset : undefined
} as MarkSymbolizer;
} else {
// icon
const olIconStyle = olStyle.getImage() as OlStyleIcon;
const displacement = olIconStyle.getDisplacement() as [number, number];
// initialOptions_ as fallback when image is not yet loaded
const image = this.getImageFromIconStyle(olIconStyle);
// this always gets calculated from ol so this might not have been set initially
let size = olIconStyle.getWidth();
const rotation = olIconStyle.getRotation() / Math.PI * 180;
const opacity = olIconStyle.getOpacity();
const iconSymbolizer: IconSymbolizer = {
kind: 'Icon',
image,
opacity: opacity < 1 ? opacity : undefined,
size,
// Rotation in openlayers is radians while we use degree
rotate: rotation !== 0 ? rotation : undefined,
offset: displacement[0] || displacement[1] ? displacement : undefined
};
pointSymbolizer = iconSymbolizer;
}
return pointSymbolizer;
}
/**
*
* @param olIconStyle An ol style Icon representation
* @returns A string or Sprite configuration
*/
getImageFromIconStyle(olIconStyle: OlStyleIcon): IconSymbolizer['image'] {
const size = olIconStyle.getSize();
if (Array.isArray(size)) {
// TODO: create getters (and setters?) in openlayers
// @ts-ignore
let position = olIconStyle.offset_ as [number, number];
// @ts-ignore
const offsetOrigin = olIconStyle.offsetOrigin_ as string;
if (offsetOrigin && offsetOrigin !== 'top-left') {
throw new Error(`Offset origin ${offsetOrigin} not supported`);
}
return {
source: olIconStyle.getSrc()!,
position,
size: size as [number, number]
};
} else {
return olIconStyle.getSrc() ? olIconStyle.getSrc() : undefined;
}
}
/**
* Get the GeoStyler-Style LineSymbolizer from an OpenLayers Style object.
*
* @param olStyle The OpenLayers Style object
* @return The GeoStyler-Style LineSymbolizer
*/
getLineSymbolizerFromOlStyle(olStyle: OlStyle): LineSymbolizer {
const olStrokeStyle = olStyle.getStroke();
// getLineDash returns null not undefined. So we have to double check
const dashArray = olStrokeStyle ? olStrokeStyle.getLineDash() : undefined;
return {
kind: 'Line',
color: olStrokeStyle ? OlStyleUtil.getHexColor(olStrokeStyle.getColor() as string) as string : undefined,
opacity: olStrokeStyle ? OlStyleUtil.getOpacity(olStrokeStyle.getColor() as string) : undefined,
width: olStrokeStyle ? olStrokeStyle.getWidth() : undefined,
cap: olStrokeStyle ? <LineSymbolizer['cap']> olStrokeStyle.getLineCap() : 'butt',
join: olStrokeStyle ? <LineSymbolizer['join']> olStrokeStyle.getLineJoin() : 'miter',
dasharray: dashArray ? dashArray : undefined,
dashOffset: olStrokeStyle ? olStrokeStyle.getLineDashOffset() : undefined
};
}
/**
* Get the GeoStyler-Style FillSymbolizer from an OpenLayers Style object.
*
* PolygonSymbolizer Stroke is just partially supported.
*
* @param olStyle The OpenLayers Style object
* @return The GeoStyler-Style FillSymbolizer
*/
getFillSymbolizerFromOlStyle(olStyle: OlStyle): FillSymbolizer {
const olFillStyle = olStyle.getFill();
const olStrokeStyle = olStyle.getStroke();
// getLineDash returns null not undefined. So we have to double check
const outlineDashArray = olStrokeStyle ? olStrokeStyle.getLineDash() : undefined;
const symbolizer: FillSymbolizer = {
kind: 'Fill'
};
if (olFillStyle) {
symbolizer.color = OlStyleUtil.getHexColor(olFillStyle.getColor() as string);
}
if (olFillStyle) {
symbolizer.fillOpacity = OlStyleUtil.getOpacity(olFillStyle.getColor() as string);
}
if (olStrokeStyle) {
symbolizer.outlineColor = OlStyleUtil.getHexColor(olStrokeStyle.getColor() as string);
}
if (outlineDashArray) {
symbolizer.outlineDasharray = outlineDashArray;
}
if (olStrokeStyle) {
symbolizer.outlineOpacity = OlStyleUtil.getOpacity(olStrokeStyle.getColor() as string);
}
if (olStrokeStyle && olStrokeStyle.getWidth()) {
symbolizer.outlineWidth = olStrokeStyle.getWidth();
}
return symbolizer;
}
/**
* Get the GeoStyler-Style TextSymbolizer from an OpenLayers Style object.
*
*
* @param olStyle The OpenLayers Style object
* @return The GeoStyler-Style TextSymbolizer
*/
getTextSymbolizerFromOlStyle(olStyle: OlStyle): TextSymbolizer {
const olTextStyle = olStyle.getText();
if (!olTextStyle) {
throw new Error('Could not get text from olStyle.');
}
const olFillStyle = olTextStyle.getFill();
const olStrokeStyle = olTextStyle.getStroke();
const offsetX = olTextStyle.getOffsetX();
const offsetY = olTextStyle.getOffsetY();
const font = olTextStyle.getFont();
const rotation = olTextStyle.getRotation();
const allowOverlap = olTextStyle.getOverflow() ? olTextStyle.getOverflow() : undefined;
const placement = olTextStyle.getPlacement();
const text = olTextStyle.getText();
const label = Array.isArray(text) ? text[0] : text;
let fontSize: number = Infinity;
let fontFamily: string[]|undefined = undefined;
let fontWeight: 'normal' | 'bold' | undefined = undefined;
let fontStyle: 'normal' | 'italic' | 'oblique' | undefined = undefined;
if (font) {
const fontObj = parseFont(font);
if (fontObj['font-weight']) {
fontWeight = fontObj['font-weight'];
}
if (fontObj['font-size']) {
fontSize = parseInt(fontObj['font-size'], 10);
}
if (fontObj['font-family']) {
const fontFamilies = fontObj['font-family'];
fontFamily = fontFamilies?.map((f: string) => f.includes(' ') ? '"' + f + '"' : f);
}
if (fontObj['font-style']) {
fontStyle = fontObj['font-style'];
}
}
return {
kind: 'Text',
label,
placement,
allowOverlap,
color: olFillStyle ? OlStyleUtil.getHexColor(olFillStyle.getColor() as string) : undefined,
size: isFinite(fontSize) ? fontSize : undefined,
font: fontFamily,
fontWeight: fontWeight || undefined,
fontStyle: fontStyle || undefined,
offset: (offsetX !== undefined) && (offsetY !== undefined) ? [offsetX, offsetY] : [0, 0],
haloColor: olStrokeStyle && olStrokeStyle.getColor() ?
OlStyleUtil.getHexColor(olStrokeStyle.getColor() as string) : undefined,
haloWidth: olStrokeStyle ? olStrokeStyle.getWidth() : undefined,
rotate: (rotation !== undefined) ? rotation / Math.PI * 180 : undefined
};
}
/**
* Get the GeoStyler-Style Symbolizer from an OpenLayers Style object.
*
* @param olStyles The OpenLayers Style object
* @return The GeoStyler-Style Symbolizer array
*/
getSymbolizersFromOlStyle(olStyles: OlStyle[]): Symbolizer[] {
const symbolizers: Symbolizer[] = [];
olStyles.forEach(olStyle => {
let symbolizer: Symbolizer;
const styleType: StyleType = this.getStyleTypeFromOlStyle(olStyle);
switch (styleType) {
case 'Point':
if (olStyle.getText() && !OlStyleUtil.getIsMarkSymbolizerFont((olStyle as any).getText().getFont())) {
symbolizer = this.getTextSymbolizerFromOlStyle(olStyle);
} else {
symbolizer = this.getPointSymbolizerFromOlStyle(olStyle);
}
break;
case 'Line':
symbolizer = this.getLineSymbolizerFromOlStyle(olStyle);
break;
case 'Fill':
symbolizer = this.getFillSymbolizerFromOlStyle(olStyle);
break;
default:
throw new Error('Failed to parse SymbolizerKind from OpenLayers Style');
}
symbolizers.push(symbolizer);
});
return symbolizers;
}
/**
* Get the GeoStyler-Style Rule from an OpenLayers Style object.
*
* @param olStyles The OpenLayers Style object
* @return The GeoStyler-Style Rule
*/
getRuleFromOlStyle(olStyles: OlStyle | OlStyle[]): Rule {
let symbolizers: Symbolizer[];
const name = 'OL Style Rule 0';
if (Array.isArray(olStyles)) {
symbolizers = this.getSymbolizersFromOlStyle(olStyles);
} else {
symbolizers = this.getSymbolizersFromOlStyle([olStyles]);
}
return {
name, symbolizers
};
}
/**
* Get the GeoStyler-Style Symbolizer from an OpenLayers Style object.
*
* @param olStyle The OpenLayers Style object
* @return The GeoStyler-Style Symbolizer
*/
getStyleTypeFromOlStyle(olStyle: OlStyle): StyleType {
let styleType: StyleType;
if (olStyle.getImage() instanceof this.OlStyleImageConstructor) {
styleType = 'Point';
} else if (olStyle.getText() instanceof this.OlStyleTextConstructor) {
styleType = 'Point';
} else if (olStyle.getFill() instanceof this.OlStyleFillConstructor) {
styleType = 'Fill';
} else if (olStyle.getStroke() && !olStyle.getFill()) {
styleType = 'Line';
} else {
throw new Error('StyleType could not be detected');
}
return styleType;
}
/**
* Get the GeoStyler-Style Style from an OpenLayers Style object.
*
* @param olStyle The OpenLayers Style object
* @return The GeoStyler-Style Style
*/
olStyleToGeoStylerStyle(olStyle: OlStyle | OlStyle[]): Style {
const name = 'OL Style';
const rule = this.getRuleFromOlStyle(olStyle);
return {
name,
rules: [rule]
};
}
/**
* The readStyle implementation of the GeoStyler-Style StyleParser interface.
* It reads an OpenLayers Style, an array of OpenLayers Styles or an olParserStyleFct and returns a Promise.
*
* The Promise itself resolves with a GeoStyler-Style Style.
*
* @param olStyle The style to be parsed
* @return The Promise resolving with the GeoStyler-Style Style
*/
readStyle(olStyle: OlStyleLike): Promise<ReadStyleResult> {
return new Promise<ReadStyleResult>((resolve) => {
try {
if (this.isOlParserStyleFct(olStyle)) {
resolve({
output: olStyle.__geoStylerStyle
});
} else {
olStyle = olStyle as OlStyle | OlStyle[];
const geoStylerStyle: Style = this.olStyleToGeoStylerStyle(olStyle);
const unsupportedProperties = this.checkForUnsupportedProperties(geoStylerStyle);
resolve({
output: geoStylerStyle,
unsupportedProperties
});
}
} catch (error) {
resolve({
errors: [error]
});
}
});
}
/**
* The writeStyle implementation of the GeoStyler-Style StyleParser interface.
* It reads a GeoStyler-Style Style and returns a Promise.
* The Promise itself resolves one of three types
*
* 1. OlStyle if input Style consists of
* one rule with one symbolizer, no filter, no scaleDenominator, no TextSymbolizer
* 2. OlStyle[] if input Style consists of
* one rule with multiple symbolizers, no filter, no scaleDenominator, no TextSymbolizer
* 3. OlParserStyleFct for everything else
*
* @param geoStylerStyle A GeoStyler-Style Style.
* @return The Promise resolving with one of above mentioned style types.
*/
writeStyle(geoStylerStyle: Style): Promise<WriteStyleResult<OlStyle | OlStyle[] | OlParserStyleFct>> {
return new Promise<WriteStyleResult>((resolve) => {
const clonedStyle = structuredClone(geoStylerStyle);
const unsupportedProperties = this.checkForUnsupportedProperties(clonedStyle);
try {
const olStyle = this.getOlStyleTypeFromGeoStylerStyle(clonedStyle);
resolve({
output: olStyle,
unsupportedProperties,
warnings: unsupportedProperties && ['Your style contains unsupportedProperties!']
});
} catch (error) {
resolve({
errors: [error]
});
}
});
}
checkForUnsupportedProperties(geoStylerStyle: Style): UnsupportedProperties | undefined {
const capitalizeFirstLetter = (a: string) => a[0].toUpperCase() + a.slice(1);
const unsupportedProperties: UnsupportedProperties = {};
geoStylerStyle.rules.forEach(rule => {
// ScaleDenominator and Filters are completly supported so we just check for symbolizers
rule.symbolizers.forEach(symbolizer => {
const key = capitalizeFirstLetter(`${symbolizer.kind}Symbolizer`);
const value = this.unsupportedProperties?.Symbolizer?.[key as SymbolizerKeyType];
if (value) {
if (typeof value === 'string') {
if (!unsupportedProperties.Symbolizer) {
unsupportedProperties.Symbolizer = {};
}
unsupportedProperties.Symbolizer[key as SymbolizerKeyType] = value;
} else {
Object.keys(symbolizer).forEach(property => {
if (value[property]) {
if (!unsupportedProperties.Symbolizer) {
unsupportedProperties.Symbolizer = {};
}
if (!unsupportedProperties.Symbolizer[key as SymbolizerKeyType]) {
(unsupportedProperties.Symbolizer as any)[key] = {};
}
unsupportedProperties.Symbolizer
[key as SymbolizerKeyType][property] = value[property];
}
});
}
}
});
});
if (Object.keys(unsupportedProperties).length > 0) {
return unsupportedProperties;
}
return undefined;
}
/**
* Decides which OlStyleType should be returned depending on given geoStylerStyle.
* Three OlStyleTypes are possible:
*
* 1. OlStyle if input Style consists of
* one rule with one symbolizer, no filter, no scaleDenominator, no TextSymbolizer
* 2. OlStyle[] if input Style consists of
* one rule with multiple symbolizers, no filter, no scaleDenominator, no TextSymbolizer
* 3. OlParserStyleFct for everything else
*
* @param geoStylerStyle A GeoStyler-Style Style
*/
getOlStyleTypeFromGeoStylerStyle(geoStylerStyle: Style): OlStyle | OlStyle[] | OlParserStyleFct {
const rules = geoStylerStyle.rules;
const nrRules = rules.length;
if (nrRules === 1) {
const hasFilter = geoStylerStyle?.rules?.[0]?.filter !== undefined ? true : false;
const hasMinScale = geoStylerStyle?.rules?.[0]?.scaleDenominator?.min !== undefined ? true : false;
const hasMaxScale = geoStylerStyle?.rules?.[0]?.scaleDenominator?.max !== undefined ? true : false;
const hasScaleDenominator = hasMinScale || hasMaxScale ? true : false;
const hasFunctions = OlStyleUtil.containsGeoStylerFunctions(geoStylerStyle);
const nrSymbolizers = geoStylerStyle.rules[0].symbolizers.length;
const hasTextSymbolizer = rules[0].symbolizers.some((symbolizer: Symbolizer) => {
return symbolizer.kind === 'Text';
});
const hasDynamicIconSymbolizer = rules[0].symbolizers.some((symbolizer: Symbolizer) => {
return symbolizer.kind === 'Icon' && typeof(symbolizer.image) === 'string' && symbolizer.image.includes('{{');
});
if (!hasFilter && !hasScaleDenominator && !hasTextSymbolizer && !hasDynamicIconSymbolizer && !hasFunctions) {
if (nrSymbolizers === 1) {
return this.geoStylerStyleToOlStyle(geoStylerStyle);
} else {
return this.geoStylerStyleToOlStyleArray(geoStylerStyle);
}
} else {
return this.geoStylerStyleToOlParserStyleFct(geoStylerStyle);
}
} else {
return this.geoStylerStyleToOlParserStyleFct(geoStylerStyle);
}
}
/**
* Parses the first symbolizer of the first rule of a GeoStyler-Style Style.
*
* @param geoStylerStyle GeoStyler-Style Style
* @return An OpenLayers Style Object
*/
geoStylerStyleToOlStyle(geoStylerStyle: Style): OlStyle {
const rule = geoStylerStyle.rules[0];
const symbolizer = rule.symbolizers[0];
const olSymbolizer = this.getOlSymbolizerFromSymbolizer(symbolizer);
return olSymbolizer;
}
/**
* Parses all symbolizers of the first rule of a GeoStyler-Style Style.
*
* @param geoStylerStyle GeoStyler-Style Style
* @return An array of OpenLayers Style Objects
*/
geoStylerStyleToOlStyleArray(geoStylerStyle: Style): OlStyle[] {
const rule = geoStylerStyle.rules[0];
const olStyles: any[] = [];
rule.symbolizers.forEach((symbolizer: Symbolizer) => {
const olSymbolizer: any = this.getOlSymbolizerFromSymbolizer(symbolizer);
olStyles.push(olSymbolizer);
});
return olStyles;
}
/**
* Get the OpenLayers Style object from an GeoStyler-Style Style
*
* @param geoStylerStyle A GeoStyler-Style Style.
* @return An OlParserStyleFct
*/
geoStylerStyleToOlParserStyleFct(geoStylerStyle: Style): OlParserStyleFct {
const rules = structuredClone(geoStylerStyle.rules);
const olStyle = (feature: any, resolution: number): any[] => {
const styles: any[] = [];
// calculate scale for resolution (from ol-util MapUtil)
const dpi = 25.4 / 0.28;
const mpu = METERS_PER_UNIT.m;
const inchesPerMeter = 39.37;
const scale = resolution * mpu * inchesPerMeter * dpi;
rules.forEach((rule: Rule) => {
// handling scale denominator
let minScale = rule?.scaleDenominator?.min;
let maxScale = rule?.scaleDenominator?.max;
let isWithinScale = true;
if (minScale || maxScale) {
minScale = isGeoStylerFunction(minScale) ? OlStyleUtil.evaluateNumberFunction(minScale) : minScale;
maxScale = isGeoStylerFunction(maxScale) ? OlStyleUtil.evaluateNumberFunction(maxScale) : maxScale;
if (minScale && scale < minScale) {
isWithinScale = false;
}
if (maxScale && scale >= maxScale) {
isWithinScale = false;
}
}
// handling filter
let matchesFilter: boolean = false;
if (!rule.filter) {
matchesFilter = true;
} else {
try {
matchesFilter = this.geoStylerFilterToOlParserFilter(feature, rule.filter);
} catch (e) {
matchesFilter = false;
}
}
if (isWithinScale && matchesFilter) {
rule.symbolizers.forEach((symb: Symbolizer) => {
if (symb.visibility === false) {
styles.push(null);
}
if (isGeoStylerBooleanFunction(symb.visibility)) {
const visibility = OlStyleUtil.evaluateBooleanFunction(symb.visibility);
if (!visibility) {
styles.push(null);
}
}
const olSymbolizer: any = this.getOlSymbolizerFromSymbolizer(symb, feature);
// either an OlStyle or an ol.StyleFunction. OpenLayers only accepts an array
// of OlStyles, not ol.StyleFunctions.
// So we have to check it and in case of an ol.StyleFunction call that function
// and add the returned style to const styles.
if (typeof olSymbolizer !== 'function') {
styles.push(olSymbolizer);
} else {
const styleFromFct: any = olSymbolizer(feature, resolution);
styles.push(styleFromFct);
}
});
}
});
return styles;
};
const olStyleFct: OlParserStyleFct = olStyle as OlParserStyleFct;
olStyleFct.__geoStylerStyle = geoStylerStyle;
return olStyleFct;
}
/**
* Checks if a feature matches given filter expression(s)
* @param feature ol.Feature
* @param filter Filter
* @return boolean true if feature matches filter expression
*/
geoStylerFilterToOlParserFilter(feature: any, filter: Filter): boolean {
const operatorMapping: any = {
'&&': true,
'||': true,
'!': true
};
let matchesFilter: boolean = true;
if (isGeoStylerBooleanFunction(filter)) {
return OlStyleUtil.evaluateBooleanFunction(filter, feature);
}
if (filter === true || filter === false) {
return filter;
}
const operator: Operator = filter[0];
let isNestedFilter: boolean = false;
if (operatorMapping[operator]) {
isNestedFilter = true;
}
try {
if (isNestedFilter) {
let intermediate: boolean;
let restFilter: any;
switch (filter[0]) {
case '&&':
intermediate = true;
restFilter = filter.slice(1);
restFilter.forEach((f: Filter) => {
if (!this.geoStylerFilterToOlParserFilter(feature, f)) {
intermediate = false;
}
});
matchesFilter = intermediate;
break;
case '||':
intermediate = false;
restFilter = filter.slice(1);
restFilter.forEach((f: Filter) => {
if (this.geoStylerFilterToOlParserFilter(feature, f)) {
intermediate = true;
}
});
matchesFilter = intermediate;
break;
case '!':
matchesFilter = !this.geoStylerFilterToOlParserFilter(feature, filter[1]);
break;
default:
throw new Error('Cannot parse Filter. Unknown combination or negation operator.');
}
} else {
let arg1: any;
if (isGeoStylerFunction(filter[1])) {
arg1 = OlStyleUtil.evaluateFunction(filter[1], feature);
} else {
arg1 = feature.get(filter[1]);
}
let arg2: any;
if (isGeoStylerFunction(filter[2])) {
arg2 = OlStyleUtil.evaluateFunction(filter[2], feature);
} else {
arg2 = filter[2];
}
switch (filter[0]) {
case '==':
matchesFilter = ('' + arg1) === ('' + arg2);
break;
case '*=':
// inspired by
// https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill
if (typeof arg2 === 'string' && typeof arg1 === 'string') {
if (arg2.length > arg1.length) {
matchesFilter = false;
} else {
matchesFilter = arg1.indexOf(arg2) !== -1;
}
}
break;
case '!=':
matchesFilter = ('' + arg1) !== ('' + arg2);
break;
case '<':
matchesFilter = Number(arg1) < Number(arg2);
break;
case '<=':
matchesFilter = Number(arg1) <= Number(arg2);
break;
case '>':
matchesFilter = Number(arg1) > Number(arg2);
break;
case '>=':
matchesFilter = Number(arg1) >= Number(arg2);
break;
default:
throw new Error('Cannot parse Filter. Unknown comparison operator.');
}
}
} catch (e) {
throw new Error('Cannot parse Filter. Invalid structure.');
}
return matchesFilter;
}
/**
* Get the OpenLayers Style object or an OL StyleFunction from an
* GeoStyler-Style Symbolizer.
*
* @param symbolizer A GeoStyler-Style Symbolizer.
* @return The OpenLayers Style object or a StyleFunction
*/
getOlSymbolizerFromSymbolizer(symbolizer: Symbolizer, feature?: OlFeature): OlStyle {
let olSymbolizer: any;
symbolizer = structuredClone(symbolizer);
switch (symbolizer.kind) {
case 'Mark':
olSymbolizer = this.getOlPointSymbolizerFromMarkSymbolizer(symbolizer, feature);
break;
case 'Icon':
olSymbolizer = this.getOlIconSymbolizerFromIconSymbolizer(symbolizer, feature);
break;
case 'Text':
olSymbolizer = this.getOlTextSymbolizerFromTextSymbolizer(symbolizer, feature);
break;
case 'Line':
olSymbolizer = this.getOlLineSymbolizerFromLineSymbolizer(symbolizer, feature);
break;
case 'Fill':
olSymbolizer = this.getOlPolygonSymbolizerFromFillSymbolizer(symbolizer, feature);
break;
default:
// Return the OL default style since the TS type binding does not allow
// us to set olSymbolizer to undefined
const fill = new this.OlStyleFillConstructor({
color: 'rgba(255,255,255,0.4)'
});
const stroke = new this.OlStyleStrokeConstructor({
color: '#3399CC',
width: 1.25
});
olSymbolizer = new this.OlStyleConstructor({
image: new this.OlStyleCircleConstructor({
fill: fill,
stroke: stroke,
radius: 5
}),
fill: fill,
stroke: stroke
});
break;
}
return olSymbolizer;