-
Notifications
You must be signed in to change notification settings - Fork 28
/
MapWrapper_openlayers.js
1617 lines (1503 loc) · 57.6 KB
/
MapWrapper_openlayers.js
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 Immutable from "immutable";
import moment from "moment";
import Ol_Map from "ol/map";
import Ol_View from "ol/view";
import Ol_Layer_Vector from "ol/layer/vector";
import Ol_Layer_Tile from "ol/layer/tile";
import Ol_Source_WMTS from "ol/source/wmts";
import Ol_Source_Cluster from "ol/source/cluster";
import Ol_Source_Vector from "ol/source/vector";
import Ol_Source_XYZ from "ol/source/xyz";
import Ol_Tilegrid_WMTS from "ol/tilegrid/wmts";
import Ol_Style_Fill from "ol/style/fill";
import Ol_Style from "ol/style/style";
import Ol_Style_Circle from "ol/style/circle";
import Ol_Style_Stroke from "ol/style/stroke";
import Ol_Proj from "ol/proj";
import Ol_Proj_Projection from "ol/proj/projection";
import Ol_Interaction from "ol/interaction";
import Ol_Interaction_Draw from "ol/interaction/draw";
import Ol_Interaction_DoubleClickZoom from "ol/interaction/doubleclickzoom";
import Ol_Overlay from "ol/overlay";
import Ol_Feature from "ol/feature";
import Ol_Geom_Circle from "ol/geom/circle";
import Ol_Geom_Linestring from "ol/geom/linestring";
import Ol_Geom_Polygon from "ol/geom/polygon";
import Ol_Format_GeoJSON from "ol/format/geojson";
import Ol_Format_TopoJSON from "ol/format/topojson";
import Ol_Format_KML from "ol/format/kml";
import Ol_Format_WMTSCapabilities from "ol/format/wmtscapabilities";
import Ol_Easing from "ol/easing";
import proj4js from "proj4";
import * as appStrings from "_core/constants/appStrings";
import appConfig from "constants/appConfig";
import MapWrapper from "_core/utils/MapWrapper";
import MiscUtil from "_core/utils/MiscUtil";
import MapUtil from "_core/utils/MapUtil";
import TileHandler from "_core/utils/TileHandler";
import Cache from "_core/utils/Cache";
export default class MapWrapper_openlayers extends MapWrapper {
constructor(container, options) {
super(container, options);
this.is3D = false;
this.isActive = !options.getIn(["view", "in3DMode"]);
this.layerCache = new Cache(appConfig.MAX_LAYER_CACHE);
this.tileHandler = TileHandler;
this.mapUtil = MapUtil;
this.miscUtil = MiscUtil;
this.cachedGeometry = null;
this.defaultGeometryStyle = new Ol_Style({
fill: new Ol_Style_Fill({
color: appConfig.GEOMETRY_FILL_COLOR
}),
stroke: new Ol_Style_Stroke({
color: appConfig.GEOMETRY_STROKE_COLOR,
width: appConfig.GEOMETRY_STROKE_WEIGHT
}),
image: new Ol_Style_Circle({
radius: 7,
fill: new Ol_Style_Fill({
color: "#ffcc33"
})
})
});
this.defaultMeasureStyle = new Ol_Style({
fill: new Ol_Style_Fill({
color: appConfig.MEASURE_FILL_COLOR
}),
stroke: new Ol_Style_Stroke({
color: appConfig.MEASURE_STROKE_COLOR,
lineDash: [10, 10],
width: 2
}),
image: new Ol_Style_Circle({
radius: 7,
stroke: new Ol_Style_Stroke({
color: "rgba(255, 255, 255, 0.75)"
}),
fill: new Ol_Style_Fill({
color: "rgba(255, 255, 255, 0.5)"
})
})
});
this.map = this.createMap(container, options);
this.initializationSuccess = this.map ? true : false;
}
createMap(container, options) {
try {
// create default draw layer
let vectorSource = new Ol_Source_Vector({ wrapX: true });
let vectorLayer = new Ol_Layer_Vector({
source: vectorSource,
style: this.defaultGeometryStyle,
extent: appConfig.DEFAULT_MAP_EXTENT
});
vectorLayer.set("_layerId", "_vector_drawings");
vectorLayer.set("_layerType", appStrings.LAYER_GROUP_TYPE_REFERENCE);
// get the view options for the map
let viewOptions = options.get("view").toJS();
let mapProjection = Ol_Proj.get(appConfig.DEFAULT_PROJECTION.code);
let center = viewOptions.center;
return new Ol_Map({
target: container,
renderer: ["canvas", "dom"],
layers: [vectorLayer],
view: new Ol_View({
maxZoom: viewOptions.maxZoom,
minZoom: viewOptions.minZoom,
projection: mapProjection,
maxResolution: viewOptions.maxResolution
}),
controls: [],
interactions: Ol_Interaction.defaults({
altShiftDragRotate: false,
pinchRotate: false,
shiftDragZoom: false,
keyboard: false
})
});
} catch (err) {
console.warn("Error in MapWrapper_openlayers.createMap:", err);
return false;
}
}
getMapSize() {
try {
let size = this.map.getSize();
if (!size) {
return { width: 0, height: 0 };
} else {
return { width: size[0], height: size[1] };
}
} catch (err) {
console.warn("Error in MapWrapper_openlayers.getMapSize:", err);
return false;
}
}
resize() {
try {
this.map.updateSize();
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.resize:", err);
return false;
}
}
createLayer(layer, fromCache = true) {
let mapLayer = false;
// pull from cache if possible
let cacheHash = this.getCacheHash(layer);
if (fromCache && this.layerCache.get(cacheHash)) {
let cachedLayer = this.layerCache.get(cacheHash);
cachedLayer.setOpacity(layer.get("opacity"));
cachedLayer.setVisible(layer.get("isActive"));
return cachedLayer;
}
switch (layer.get("handleAs")) {
case appStrings.LAYER_GIBS_RASTER:
mapLayer = this.createWMTSLayer(layer, fromCache);
break;
case appStrings.LAYER_WMTS_RASTER:
mapLayer = this.createWMTSLayer(layer, fromCache);
break;
case appStrings.LAYER_XYZ_RASTER:
mapLayer = this.createWMTSLayer(layer, fromCache);
break;
case appStrings.LAYER_VECTOR_GEOJSON:
mapLayer = this.createVectorLayer(layer, fromCache);
break;
case appStrings.LAYER_VECTOR_TOPOJSON:
mapLayer = this.createVectorLayer(layer, fromCache);
break;
case appStrings.LAYER_VECTOR_KML:
mapLayer = this.createVectorLayer(layer, fromCache);
break;
default:
console.warn(
"Error in MapWrapper_openlayers.createLayer: unknown layer type - ",
layer.get("handleAs")
);
mapLayer = false;
break;
}
if (mapLayer) {
mapLayer.set("_layerId", layer.get("id"));
mapLayer.set("_layerType", layer.get("type"));
mapLayer.set("_layerCacheHash", this.getCacheHash(layer));
mapLayer.set("_layerTime", moment(this.mapDate).format(layer.get("timeFormat")));
}
return mapLayer;
}
createWMTSLayer(layer, fromCache = true) {
try {
if (layer && layer.get("wmtsOptions")) {
let options = layer.get("wmtsOptions").toJS();
let layerSource = this.createLayerSource(layer, options);
// set up wrap around extents
// let mapProjExtent = this.map.getView().getProjection().getExtent();
let mapLayer = new Ol_Layer_Tile({
opacity: layer.get("opacity"),
visible: layer.get("isActive"),
crossOrigin: "anonymous",
source: layerSource,
extent: appConfig.DEFAULT_MAP_EXTENT
});
// override tile url and load functions
let origTileUrlFunc = layerSource.getTileUrlFunction();
let origTileLoadFunc = layerSource.getTileLoadFunction();
layerSource.setTileUrlFunction((tileCoord, pixelRatio, projectionString) => {
return this.generateTileUrl(
layer,
mapLayer,
layerSource,
tileCoord,
pixelRatio,
projectionString,
origTileUrlFunc
);
});
layerSource.setTileLoadFunction((tile, url) => {
return this.handleTileLoad(layer, mapLayer, tile, url, origTileLoadFunc);
});
return mapLayer;
}
return false;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.createWMTSLayer:", err);
return false;
}
}
createVectorLayer(layer, fromCache = true) {
try {
let layerSource = this.createLayerSource(layer, {
url: layer.get("url")
});
if (layer.get("clusterVector")) {
layerSource = new Ol_Source_Cluster({ source: layerSource });
}
return new Ol_Layer_Vector({
source: layerSource,
opacity: layer.get("opacity"),
visible: layer.get("isActive"),
extent: appConfig.DEFAULT_MAP_EXTENT
});
} catch (err) {
console.warn("Error in MapWrapper_openlayers.createVectorLayer:", err);
return false;
}
}
getCenter() {
return [0, 0];
}
setExtent(extent) {
try {
if (extent) {
let mapSize = this.map.getSize() || [];
this.map.getView().fit(extent, {
size: mapSize,
constrainResolution: false
});
return true;
}
return false;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.setExtent:", err);
return false;
}
}
getExtent() {
try {
return this.map.getView().calculateExtent(this.map.getSize());
} catch (err) {
console.warn("Error in MapWrapper_openlayers.getExtent:", err);
return false;
}
}
panMap(direction, extraFar) {
try {
let deltaX = 0;
let deltaY = 0;
let view = this.map.getView();
let pixelDelta = extraFar ? 200 : 100;
switch (direction) {
case appStrings.MAP_PAN_DIRECTION_UP:
deltaY = pixelDelta;
break;
case appStrings.MAP_PAN_DIRECTION_DOWN:
deltaY = -pixelDelta;
break;
case appStrings.MAP_PAN_DIRECTION_LEFT:
deltaX = pixelDelta;
break;
case appStrings.MAP_PAN_DIRECTION_RIGHT:
deltaX = -pixelDelta;
break;
default:
return false;
}
let delta = [deltaX, deltaY];
let centerInPx = this.map.getPixelFromCoordinate(view.getCenter());
let newCenterInPx = [centerInPx[0] - delta[0], centerInPx[1] - delta[1]];
let newCenter = this.map.getCoordinateFromPixel(newCenterInPx);
this.map.getView().setCenter(this.map.getView().getCenter());
let pan = this.map.getView().animate({
duration: 175,
easing: Ol_Easing.linear,
center: newCenter
});
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.panMap:", err);
return false;
}
}
zoomIn(duration = 175) {
try {
if (typeof this.map !== "undefined" && typeof this.map.getView() !== "undefined") {
this.map.getView().setResolution(this.map.getView().getResolution());
this.map.getView().animate({
resolution: this.map.getView().getResolution(),
zoom: this.map.getView().getZoom() + 1,
duration: duration
});
return true;
}
return false;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.zoomIn:", err);
return false;
}
}
zoomOut(duration = 175) {
try {
if (typeof this.map !== "undefined" && typeof this.map.getView() !== "undefined") {
this.map.getView().setResolution(this.map.getView().getResolution());
this.map.getView().animate({
resolution: this.map.getView().getResolution(),
zoom: this.map.getView().getZoom() - 1,
duration: duration
});
return true;
}
return false;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.zoomOut:", err);
return false;
}
}
enableDrawing(geometryType) {
try {
// remove double-click zoom while drawing so we can double-click complete
this.setDoubleClickZoomEnabled(false);
// Get drawHandler by geometryType
let drawInteraction = this.miscUtil.findObjectInArray(
this.map.getInteractions().getArray(),
"_id",
appStrings.INTERACTION_DRAW + geometryType
);
if (drawInteraction) {
// Call setActive(true) on handler to enable
drawInteraction.setActive(true);
// Check that handler is active
return drawInteraction.getActive();
}
return false;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.enableDrawing:", err);
return false;
}
}
disableDrawing(delayDblClickEnable = true) {
try {
// Call setActive(false) on all handlers
let drawInteractions = this.miscUtil.findAllMatchingObjectsInArray(
this.map.getInteractions().getArray(),
appStrings.INTERACTION_DRAW,
true
);
drawInteractions.map(handler => {
handler.setActive(false);
// Check that handler is not active
if (handler.getActive()) {
console.warn("could not disable openlayers draw handler:", handler.get("_id"));
}
});
// re-enable double-click zoom
if (delayDblClickEnable) {
setTimeout(() => {
this.setDoubleClickZoomEnabled(true);
}, 251);
} else {
this.setDoubleClickZoomEnabled(true);
}
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.disableDrawing:", err);
return false;
}
}
completeDrawing() {
try {
let drawInteractions = this.miscUtil.findAllMatchingObjectsInArray(
this.map.getInteractions().getArray(),
appStrings.INTERACTION_DRAW,
true
);
drawInteractions.map(handler => {
if (handler.getActive()) {
handler.finishDrawing();
}
});
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.completeDrawing:", err);
return false;
}
}
enableMeasuring(geometryType, measurementType) {
try {
// remove double-click zoom while drawing so we can double-click complete
this.setDoubleClickZoomEnabled(false);
// Get drawHandler by geometryType
let interaction = this.miscUtil.findObjectInArray(
this.map.getInteractions().getArray(),
"_id",
appStrings.INTERACTION_MEASURE + geometryType
);
if (interaction) {
// Call setActive(true) on handler to enable
interaction.setActive(true);
// Check that handler is active
return interaction.getActive();
}
return false;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.enableMeasuring:", err);
return false;
}
}
disableMeasuring(delayDblClickEnable = true) {
try {
// Call setActive(false) on all handlers
let measureInteractions = this.miscUtil.findAllMatchingObjectsInArray(
this.map.getInteractions().getArray(),
appStrings.INTERACTION_MEASURE,
true
);
measureInteractions.map(handler => {
handler.setActive(false);
// Check that handler is not active
if (handler.getActive()) {
console.warn(
"could not disable openlayers measure handler:",
handler.get("_id")
);
}
});
// re-enable double-click zoom
if (delayDblClickEnable) {
setTimeout(() => {
this.setDoubleClickZoomEnabled(true);
}, 251);
} else {
this.setDoubleClickZoomEnabled(true);
}
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.disableMeasuring:", err);
return false;
}
}
completeMeasuring() {
try {
let measureInteractions = this.miscUtil.findAllMatchingObjectsInArray(
this.map.getInteractions().getArray(),
appStrings.INTERACTION_MEASURE,
true
);
measureInteractions.map(handler => {
if (handler.getActive()) {
handler.finishDrawing();
}
});
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.completeMeasuring:", err);
return false;
}
}
setDoubleClickZoomEnabled(enabled) {
try {
let dblClickInteraction = this.miscUtil.findObjectInArray(
this.map.getInteractions().getArray(),
interaction => {
return interaction instanceof Ol_Interaction_DoubleClickZoom;
}
);
if (dblClickInteraction) {
dblClickInteraction.setActive(enabled);
}
} catch (err) {
console.warn("Error in MapWrapper_openlayers.setDoubleClickZoomEnabled:", err);
return false;
}
}
enableActiveListeners(active) {
return false;
}
addGeometry(geometry, interactionType, geodesic = false) {
let mapLayers = this.map.getLayers().getArray();
let mapLayer = this.miscUtil.findObjectInArray(mapLayers, "_layerId", "_vector_drawings");
if (!mapLayer) {
console.warn("could not find drawing layer in openlayers map");
return false;
}
if (geometry.type === appStrings.GEOMETRY_CIRCLE) {
let circleGeom = null;
if (geometry.coordinateType === appStrings.COORDINATE_TYPE_CARTOGRAPHIC) {
circleGeom = new Ol_Geom_Circle(
[geometry.center.lon, geometry.center.lat],
geometry.radius /
Ol_Proj.METERS_PER_UNIT[
this.map
.getView()
.getProjection()
.getUnits()
]
);
} else {
console.warn(
"Unsupported geometry coordinateType ",
geometry.coordinateType,
" for openlayers circle"
);
return false;
}
let circleFeature = new Ol_Feature({
geometry: circleGeom
});
circleFeature.set("interactionType", interactionType);
circleFeature.setId(geometry.id);
mapLayer.getSource().addFeature(circleFeature);
return true;
}
if (geometry.type === appStrings.GEOMETRY_LINE_STRING) {
let lineStringGeom = null;
if (geometry.coordinateType === appStrings.COORDINATE_TYPE_CARTOGRAPHIC) {
let geomCoords = geometry.coordinates.map(x => {
return [x.lon, x.lat];
});
// generate geodesic arcs from points
if (geodesic) {
geomCoords = this.mapUtil.generateGeodesicArcsForLineString(geomCoords);
}
lineStringGeom = new Ol_Geom_Linestring(geomCoords);
} else {
console.warn(
"Unsupported geometry coordinateType ",
geometry.coordinateType,
" for openlayers lineString"
);
return false;
}
let lineStringFeature = new Ol_Feature({
geometry: lineStringGeom
});
lineStringFeature.set("interactionType", interactionType);
lineStringFeature.setId(geometry.id);
mapLayer.getSource().addFeature(lineStringFeature);
return true;
}
if (geometry.type === appStrings.GEOMETRY_POLYGON) {
let polygonGeom = null;
if (geometry.coordinateType === appStrings.COORDINATE_TYPE_CARTOGRAPHIC) {
// Map obj to array
let geomCoords = geometry.coordinates.map(x => {
return [x.lon, x.lat];
});
// Push the first point to close the ring
geomCoords.push([geometry.coordinates[0].lon, geometry.coordinates[0].lat]);
// generate geodesic arcs from points
if (geodesic) {
geomCoords = this.mapUtil.generateGeodesicArcsForLineString(geomCoords);
}
// Put these coordinates into a ring by adding to array
polygonGeom = new Ol_Geom_Polygon([geomCoords]);
} else {
console.warn(
"Unsupported geometry coordinateType ",
geometry.coordinateType,
" for openlayers polygon"
);
return false;
}
let polygonFeature = new Ol_Feature({
geometry: polygonGeom
});
polygonFeature.set("interactionType", interactionType);
polygonFeature.setId(geometry.id);
mapLayer.getSource().addFeature(polygonFeature);
return true;
}
return false;
}
addLabel(label, coords, opt_meta = {}) {
try {
// Create label domNode
let measureLabelEl = document.createElement("div");
measureLabelEl.className = "tooltip tooltip-static";
measureLabelEl.innerHTML = label;
// create ol overlay
let measureLabel = new Ol_Overlay({
element: measureLabelEl,
offset: [0, -15],
positioning: "bottom-center"
});
// store meta opt_meta
for (let key in opt_meta) {
if (opt_meta.hasOwnProperty(key)) {
measureLabel.set(key, opt_meta[key], true);
}
}
// position and place
measureLabel.setPosition(coords);
this.map.addOverlay(measureLabel);
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.addLabel:", err);
return false;
}
}
removeAllDrawings() {
let mapLayers = this.map.getLayers().getArray();
let mapLayer = this.miscUtil.findObjectInArray(mapLayers, "_layerId", "_vector_drawings");
if (!mapLayer) {
console.warn("could not remove all geometries in openlayers map");
return false;
}
// Remove geometries
let mapLayerFeatures = mapLayer.getSource().getFeatures();
let featuresToRemove = mapLayerFeatures.filter(
x => x.get("interactionType") === appStrings.INTERACTION_DRAW
);
for (let i = 0; i < featuresToRemove.length; i++) {
mapLayer.getSource().removeFeature(featuresToRemove[i]);
}
return (
mapLayer
.getSource()
.getFeatures()
.filter(x => x.get("interactionType") === appStrings.INTERACTION_DRAW).length === 0
);
}
removeAllMeasurements() {
let mapLayers = this.map.getLayers().getArray();
let mapLayer = this.miscUtil.findObjectInArray(mapLayers, "_layerId", "_vector_drawings");
if (!mapLayer) {
console.warn("could not remove all geometries in openlayers map");
return false;
}
// Remove geometries
let mapLayerFeatures = mapLayer.getSource().getFeatures();
let featuresToRemove = mapLayerFeatures.filter(
x => x.get("interactionType") === appStrings.INTERACTION_MEASURE
);
for (let i = 0; i < featuresToRemove.length; i++) {
mapLayer.getSource().removeFeature(featuresToRemove[i]);
}
// Remove overlays
this.map.getOverlays().clear();
return (
mapLayer
.getSource()
.getFeatures()
.filter(x => x.get("interactionType") === appStrings.INTERACTION_MEASURE).length ===
0 && this.map.getOverlays().getArray().length === 0
);
}
resetOrientation(duration) {
return true;
}
addDrawHandler(geometryType, onDrawEnd, interactionType) {
try {
let mapLayers = this.map.getLayers().getArray();
let mapLayer = this.miscUtil.findObjectInArray(
mapLayers,
"_layerId",
"_vector_drawings"
);
if (mapLayer) {
let measureDistGeom = (coords, opt_geom) => {
let geom = opt_geom ? opt_geom : new Ol_Geom_Linestring();
// remove duplicates
let newCoords = coords.reduce((acc, el, i) => {
let prev = acc[i - 1];
el = this.mapUtil.constrainCoordinates(el);
if (!prev || (prev[0] !== el[0] || prev[1] !== el[1])) {
acc.push(el);
}
return acc;
}, []);
let lineCoords = this.mapUtil.generateGeodesicArcsForLineString(newCoords);
geom.setCoordinates(lineCoords);
geom.set("originalCoordinates", newCoords, true);
return geom;
};
let measureAreaGeom = (coords, opt_geom) => {
coords = coords[0]; // TODO: find case where this isn't what we want
let geom = opt_geom ? opt_geom : new Ol_Geom_Polygon();
// remove duplicates
let newCoords = coords.reduce((acc, el, i) => {
let prev = acc[i - 1];
el = this.mapUtil.constrainCoordinates(el);
if (!prev || (prev[0] !== el[0] || prev[1] !== el[1])) {
acc.push(el);
}
return acc;
}, []);
let lineCoords = this.mapUtil.generateGeodesicArcsForLineString(newCoords);
geom.setCoordinates([lineCoords]);
geom.set("originalCoordinates", newCoords, true);
return geom;
};
let geometryFunction = undefined;
if (interactionType === appStrings.INTERACTION_MEASURE) {
if (geometryType === appStrings.GEOMETRY_LINE_STRING) {
geometryFunction = measureDistGeom;
} else if (geometryType === appStrings.GEOMETRY_POLYGON) {
geometryFunction = measureAreaGeom;
}
}
let drawStyle =
interactionType === appStrings.INTERACTION_MEASURE
? this.defaultMeasureStyle
: this.defaultGeometryStyle;
let drawInteraction = new Ol_Interaction_Draw({
source: mapLayer.getSource(),
type: geometryType,
geometryFunction: geometryFunction,
style: drawStyle,
wrapX: true
});
if (appConfig.DEFAULT_MAP_EXTENT) {
// Override creation of overlay_ so we can pass in an extent
// since OL doesn't let you do this via options
drawInteraction.overlay_ = new Ol_Layer_Vector({
extent: appConfig.DEFAULT_MAP_EXTENT,
source: new Ol_Source_Vector({
useSpatialIndex: false,
wrapX: true
}),
style: drawStyle
});
}
// Set callback
drawInteraction.on("drawend", event => {
if (typeof onDrawEnd === "function") {
// store type of feature and id for later reference
let geometry = this.retrieveGeometryFromEvent(event, geometryType);
event.feature.set("interactionType", interactionType);
event.feature.setId(geometry.id);
onDrawEnd(geometry, event);
}
});
// Disable
drawInteraction.setActive(false);
// Set properties we'll need
drawInteraction.set("_id", interactionType + geometryType);
drawInteraction.set(interactionType, true);
// Add to map
this.map.addInteraction(drawInteraction);
return true;
}
return false;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.addDrawHandler:", err);
return false;
}
}
retrieveGeometryFromEvent(event, geometryType) {
if (geometryType === appStrings.GEOMETRY_CIRCLE) {
let center = event.feature.getGeometry().getCenter();
return {
type: appStrings.GEOMETRY_CIRCLE,
id: Math.random(),
center: { lon: center[0], lat: center[1] },
radius: event.feature.getGeometry().getRadius(),
proj: this.map
.getView()
.getProjection()
.getCode(),
coordinateType: appStrings.COORDINATE_TYPE_CARTOGRAPHIC
};
} else if (geometryType === appStrings.GEOMETRY_LINE_STRING) {
let tmpCoords = [];
if (event.feature.getGeometry().get("originalCoordinates")) {
tmpCoords = event.feature
.getGeometry()
.get("originalCoordinates")
.map(x => {
return { lon: x[0], lat: x[1] };
});
} else {
tmpCoords = event.feature
.getGeometry()
.getCoordinates()
.map(x => {
return { lon: x[0], lat: x[1] };
});
}
return {
type: appStrings.GEOMETRY_LINE_STRING,
id: Math.random(),
proj: this.map
.getView()
.getProjection()
.getCode(),
coordinates: tmpCoords,
coordinateType: appStrings.COORDINATE_TYPE_CARTOGRAPHIC
};
} else if (geometryType === appStrings.GEOMETRY_POLYGON) {
let tmpCoords = [];
if (event.feature.getGeometry().get("originalCoordinates")) {
tmpCoords = event.feature
.getGeometry()
.get("originalCoordinates")
.map(x => {
return { lon: x[0], lat: x[1] };
});
} else {
tmpCoords = event.feature
.getGeometry()
.getCoordinates()[0]
.map(x => {
return { lon: x[0], lat: x[1] };
});
}
return {
type: appStrings.GEOMETRY_POLYGON,
id: Math.random(),
proj: this.map
.getView()
.getProjection()
.getCode(),
coordinates: tmpCoords,
coordinateType: appStrings.COORDINATE_TYPE_CARTOGRAPHIC
};
}
return false;
}
setScaleUnits(units) {
try {
// Set scalebar units
let controls = this.map.getControls();
controls.forEach((el, index, arr) => {
if (typeof el.setUnits === "function") {
el.setUnits(units);
}
});
// Set measurement units
this.map.getOverlays().forEach(overlay => {
if (overlay.get("measurementType") === appStrings.MEASURE_AREA) {
overlay.getElement().innerHTML = this.mapUtil.formatArea(
this.mapUtil.convertAreaUnits(overlay.get("meters"), units),
units
);
} else if (overlay.get("measurementType") === appStrings.MEASURE_DISTANCE) {
overlay.getElement().innerHTML = this.mapUtil.formatDistance(
this.mapUtil.convertDistanceUnits(overlay.get("meters"), units),
units
);
} else {
console.warn("could not set openlayers scale units.");
return false;
}
});
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.setScaleUnits:", err);
return false;
}
}
addLayer(mapLayer) {
try {
let index = this.findTopInsertIndexForLayer(mapLayer);
this.map.getLayers().insertAt(index, mapLayer);
this.layerCache.set(mapLayer.get("_layerCacheHash"), mapLayer);
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.addLayer:", err);
return false;
}
}
removeLayer(mapLayer) {
try {
this.map.removeLayer(mapLayer);
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.removeLayer:", err);
return false;
}
}
replaceLayer(mapLayer, index) {
try {
this.map.getLayers().setAt(index, mapLayer);
this.layerCache.set(mapLayer.get("_layerCacheHash"), mapLayer);
return true;
} catch (err) {
console.warn("Error in MapWrapper_openlayers.replaceLayer:", err);
return false;
}
}
activateLayer(layer) {
try {
let mapLayers = this.map.getLayers().getArray();
// check if layer already exists on map, just move to top
let mapLayer = this.miscUtil.findObjectInArray(mapLayers, "_layerId", layer.get("id"));
if (mapLayer) {
this.moveLayerToTop(layer);
return true;
}
// layer does not exist so we must create it
mapLayer = this.createLayer(layer);
// if the creation failed
if (!mapLayer) {
return false;
}