-
Notifications
You must be signed in to change notification settings - Fork 88
/
Snapping.js
896 lines (788 loc) · 26.9 KB
/
Snapping.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
// The MIT License (MIT)
//
// Copyright (c) 2016-2022 Camptocamp SA
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import angular from 'angular';
import gmfDatasourceFileGroup from 'gmf/datasource/fileGroupModule';
import gmfLayertreeTreeManager from 'gmf/layertree/TreeManager';
import gmfThemeThemes, {ThemeNodeType, getSnappingConfig} from 'gmf/theme/Themes';
import ngeoLayertreeController, {getFirstParentTree} from 'ngeo/layertree/Controller';
import ngeoDatasourceFile from 'ngeo/datasource/File';
import {DEFAULT_GEOMETRY_NAME} from 'ngeo/datasource/OGC';
import {getUid as olUtilGetUid} from 'ol/util';
import {listen, unlistenByKey} from 'ol/events';
import olCollection, {CollectionEvent} from 'ol/Collection';
import olFormatWFS from 'ol/format/WFS';
import olInteractionSnap from 'ol/interaction/Snap';
export class CustomSnap extends olInteractionSnap {
/**
* @param {import('ol/interaction/Snap').Options} options
*/
constructor(options) {
super(options);
document.body.addEventListener('keydown', (evt) => {
this.setActive(evt.keyCode !== 17); // Ctrl key
});
document.body.addEventListener('keyup', () => {
this.setActive(true);
});
}
}
/**
* The snapping service of GMF. Responsible of collecting the treeCtrls that
* support snapping and store them here. As soon as a treeCtrl state becomes
* 'on', a WFS GetFeature request is issued to collect the features at the
* map view location. A new request is sent every time the map is panned or
* zoomed for each treeCtrl that are still 'on'.
*
* Features returned by these requests get bound to a `ol.interaction.Snap`,
* which allows the snapping to occur on other places where vector
* features are drawn or modified.
*
*
* @class
* @param {angular.IHttpService} $http Angular $http service.
* @param {angular.IQService} $q The Angular $q service.
* @param {angular.IScope} $rootScope Angular rootScope.
* @param {angular.auto.IInjectorService} $injector Angular injector.
* @param {angular.ITimeoutService} $timeout Angular timeout service.
* @param {import('gmf/datasource/fileGroupModule').DatasourceFileGroup} gmfDatasourceFileGroup Group that contains file data sources.
* @param {import('gmf/themes').GmfSnappingConfig} gmfSnappingConfig Snapping configuration options for the
* features in the Draw tool and in the "Layer Import / Local" tool.
* @param {import('gmf/theme/Themes').ThemesService} gmfThemes The gmf Themes service.
* @param {import('gmf/layertree/TreeManager').LayertreeTreeManager} gmfTreeManager The gmf TreeManager
* service.
* @param {import('ol/Collection').default<import('ol/Feature').default<import('ol/geom/Geometry').default>>} ngeoFeatures Collection
* of features.
* @param {import('gmf/options.js').gmfSnappingOptions} gmfSnappingOptions The options.
* @ngInject
* @ngdoc service
* @ngname gmfSnapping
*/
export function EditingSnappingService(
$http,
$q,
$rootScope,
$injector,
$timeout,
gmfDatasourceFileGroup,
gmfSnappingConfig,
gmfThemes,
gmfTreeManager,
ngeoFeatures,
gmfSnappingOptions
) {
// === Injected services ===
/**
* @type {angular.IHttpService}
*/
this.http_ = $http;
/**
* @type {angular.IQService}
*/
this.q_ = $q;
/**
* @type {angular.IScope}
*/
this.rootScope_ = $rootScope;
/**
* @type {angular.ITimeoutService}
*/
this.timeout_ = $timeout;
/**
* @type {angular.auto.IInjectorService}
*/
this.injector_ = $injector;
/**
* @type {import('gmf/datasource/fileGroupModule').DatasourceFileGroup}
*/
this.gmfDatasourceFileGroup_ = gmfDatasourceFileGroup;
/**
* @type {import('gmf/themes').GmfSnappingConfig}
*/
this.gmfSnappingConfig_ = gmfSnappingConfig;
/**
* @type {import('gmf/options.js').gmfSnappingOptions}
*/
this.gmfSnappingOptions_ = gmfSnappingOptions;
/**
* @type {import("gmf/theme/Themes.js").ThemesService}
*/
this.gmfThemes_ = gmfThemes;
/**
* @type {import('gmf/layertree/TreeManager').LayertreeTreeManager}
*/
this.gmfTreeManager_ = gmfTreeManager;
/**
* @type {import('ol/Collection').default<import('ol/Feature').default<import('ol/geom/Geometry').default>>}
*/
this.ngeoFeatures_ = ngeoFeatures;
// === Properties ===
/**
* A cache containing all available snappable items, in which the listening
* of the state of the `treeCtrl` is registered and unregistered.
*
* @type {Cache}
*/
this.cache_ = {};
/**
* A cache for the File data sources that are added in the
* FileGroup, i.e. for example when a KML is added, then a File data
* source is added to the FileGroup's collection, and their features
* need to be snappable.
*
* @type {CacheFileDataSource}
*/
this.cacheFileDataSource_ = {};
/**
* @type {import('ol/events').EventsKey[]}
*/
this.listenerKeys_ = [];
/**
* @type {?import('ol/Map').default}
*/
this.map_ = null;
/**
* Reference to the promise taking care of calling all GetFeature requests
* of the currently active cache items after the map view changed. Used
* to cancel if the map view changes often within a short period of time.
*
* @type {?angular.IPromise<void>}
*/
this.mapViewChangePromise_ = null;
/**
* @type {!CustomSnap}
*/
this.ngeoFeaturesSnapInteraction_ = new CustomSnap({
edge: gmfSnappingConfig.edge,
features: ngeoFeatures,
pixelTolerance: gmfSnappingConfig.tolerance,
vertex: gmfSnappingConfig.vertex,
});
/**
* A reference to the OGC servers loaded by the theme service.
*
* @type {import('gmf/themes').GmfOgcServers|null}
*/
this.ogcServers_ = null;
/**
* @type {import('ol/source/Vector').default<unknown>|undefined}
*/
this.ngeoSnappingSource_ = this.injector_.has('ngeoSnappingSource')
? this.injector_.get('ngeoSnappingSource')
: undefined;
}
/**
* In order for a `ol.interaction.Snap` to work properly, it has to be added
* to the map after any draw interactions or other kinds of interactions that
* interacts with features on the map.
*
* This method can be called to make sure the Snap interactions are on top.
*
*/
EditingSnappingService.prototype.ensureSnapInteractionsOnTop = function () {
if (!this.map_) {
throw new Error('Missing map');
}
const map = this.map_;
// (1) Deal with the WMS items first
let item;
for (const uid in this.cache_) {
item = this.cache_[uid];
if (item.active) {
if (!item.interaction) {
throw new Error('Missing item.interaction');
}
map.removeInteraction(item.interaction);
map.addInteraction(item.interaction);
}
}
// (2) Then with the file data source items
for (const uid in this.cacheFileDataSource_) {
item = this.cacheFileDataSource_[uid];
if (item.active) {
if (!item.interaction) {
throw new Error('Missing item.interaction');
}
map.removeInteraction(item.interaction);
map.addInteraction(item.interaction);
}
}
// (3) Finally, deal with the ngeo features, a.k.a. the features in
// the "draw" tool
map.removeInteraction(this.ngeoFeaturesSnapInteraction_);
map.addInteraction(this.ngeoFeaturesSnapInteraction_);
};
/**
* Bind the snapping service to a map
*
* @param {?import('ol/Map').default} map Map
*/
EditingSnappingService.prototype.setMap = function (map) {
const keys = this.listenerKeys_;
if (this.map_) {
if (!this.treeCtrlsUnregister_) {
throw new Error('Missing treeCtrlsUnregister');
}
this.treeCtrlsUnregister_();
this.unregisterAllTreeCtrl_();
keys.forEach(unlistenByKey);
keys.length = 0;
this.map_.removeInteraction(this.ngeoFeaturesSnapInteraction_);
}
this.map_ = map;
if (map) {
// (1) Listen to the layer tree nodes changes to manage the WMS
// (WFS) layers that support being snapped on.
this.treeCtrlsUnregister_ = this.rootScope_.$watchCollection(
() => {
if (this.gmfTreeManager_.rootCtrl) {
return this.gmfTreeManager_.rootCtrl.children;
}
},
(value) => {
// Timeout required, because the collection event is fired before the
// leaf nodes are created and they are the ones we're looking for here.
this.timeout_(() => {
if (value) {
if (!this.gmfTreeManager_.rootCtrl) {
throw new Error('Missing gmfTreeManager_.rootCtrl');
}
this.unregisterAllTreeCtrl_();
this.gmfTreeManager_.rootCtrl.traverseDepthFirst(this.registerTreeCtrl_.bind(this));
}
}, 0);
}
);
keys.push(
// (2) Listen when the themes change to reobtain the OGC servers
listen(this.gmfThemes_, 'change', this.handleThemesChange_, this),
// (3) Listen when the map is moved to update the vector
// features of the WMS (WFS) layers
listen(map, 'moveend', this.handleMapMoveEnd_, this)
);
// (4) Listen when File data sources are added to the File Group
// (i.e. when vector files are imported using the Import tool,
// they create File data sources, which contain features that have
// to be snapped on)
const fileGroup = this.gmfDatasourceFileGroup_.fileGroup;
if (fileGroup) {
keys.push(
listen(fileGroup.dataSourcesCollection, 'add', this.handleFileGroupDataSourcesCollectionAdd_, this),
listen(
fileGroup.dataSourcesCollection,
'remove',
this.handleFileGroupDataSourcesCollectionRemove_,
this
)
);
}
// (5) Enable the snapping on 'ngeo features', i.e. on features
// that are added/drawn using the Draw tool
map.addInteraction(this.ngeoFeaturesSnapInteraction_);
}
};
/**
* Called when the themes change. Get the OGC servers, then listen to the
* tree manager Layertree controllers array changes.
*/
EditingSnappingService.prototype.handleThemesChange_ = function () {
this.ogcServers_ = null;
this.gmfThemes_.getOgcServersObject().then((ogcServers) => {
this.ogcServers_ = ogcServers;
});
};
/**
* Registers a newly added Layertree controller 'leaf'. If it's snappable,
* create and add a cache item with every configuration required to do the
* snapping. It becomes active when its state is set to 'on'.
*
* @param {import('ngeo/layertree/Controller').LayertreeController} treeCtrl Layertree controller to
* register
*/
EditingSnappingService.prototype.registerTreeCtrl_ = function (treeCtrl) {
// Skip any Layertree controller that has a node that is not a leaf
let node = /** @type {import('gmf/themes').GmfGroup|import('gmf/themes').GmfLayer} */ (treeCtrl.node);
const groupNode = /** @type {import('gmf/themes').GmfGroup} */ (node);
if (groupNode.children) {
return;
}
// If treeCtrl is snappable and supports WFS, listen to its state change.
// When it becomes visible, it's added to the list of snappable tree ctrls.
node = /** @type {import('gmf/themes').GmfLayer} */ (treeCtrl.node);
const snappingConfig = getSnappingConfig(node);
const maxFeatures = this.gmfSnappingOptions_.maxFeatures || 50;
if (snappingConfig) {
const wfsConfig = this.getWFSConfig_(treeCtrl);
if (wfsConfig) {
const uid = olUtilGetUid(treeCtrl);
const stateWatcherUnregister = this.rootScope_.$watch(
() => this.isSnappingActiveForTreeCtrl_(treeCtrl),
this.handleTreeCtrlStateChange_.bind(this, treeCtrl)
);
const ogcServer = this.getOGCServer_(treeCtrl);
if (!ogcServer) {
throw new Error('Missing ogcServer');
}
this.cache_[uid] = {
active: false,
featureNS: ogcServer.wfsFeatureNS,
featurePrefix: 'feature',
features: new olCollection(),
interaction: null,
maxFeatures: maxFeatures,
requestDeferred: null,
snappingConfig: snappingConfig,
treeCtrl: treeCtrl,
wfsConfig: wfsConfig,
stateWatcherUnregister: stateWatcherUnregister,
};
// This extra call is to initialize the treeCtrl with its current state
this.handleTreeCtrlStateChange_(treeCtrl, this.isSnappingActiveForTreeCtrl_(treeCtrl));
}
}
};
/**
* Unregisters all removed layertree controllers 'leaf'. Remove the according
* cache item and deactivate it as well. Unregister events.
*/
EditingSnappingService.prototype.unregisterAllTreeCtrl_ = function () {
for (const uid in this.cache_) {
const item = this.cache_[uid];
if (item) {
item.stateWatcherUnregister();
this.deactivateItem_(item);
delete this.cache_[uid];
}
}
};
/**
* Get the OGC server.
*
* @param {import('ngeo/layertree/Controller').LayertreeController} treeCtrl The layer tree controller
* @returns {?import('gmf/themes').GmfOgcServer} The OGC server.
*/
EditingSnappingService.prototype.getOGCServer_ = function (treeCtrl) {
const gmfLayer = /** @type {import('gmf/themes').GmfLayer} */ (treeCtrl.node);
if (gmfLayer.type !== ThemeNodeType.WMS) {
return null;
}
const gmfLayerWMS = /** @type {import('gmf/themes').GmfLayerWMS} */ (/** @type {any} */ (gmfLayer));
let ogcServerName;
const gmfGroup = /** @type {import('gmf/themes').GmfGroup} */ (treeCtrl.parent.node);
if (gmfGroup.mixed) {
ogcServerName = gmfLayerWMS.ogcServer;
} else {
const firstTreeCtrl = getFirstParentTree(treeCtrl);
const firstNode = /** @type {import('gmf/themes').GmfGroup} */ (firstTreeCtrl.node);
ogcServerName = firstNode.ogcServer;
}
if (!ogcServerName) {
return null;
}
if (!this.ogcServers_) {
throw new Error('Missing ogcServers');
}
return this.ogcServers_[ogcServerName];
};
/**
* Get the configuration required to do WFS requests (for snapping purpose)
* from a Layertree controller that has a leaf node.
*
* The following requirements must be met in order for a treeCtrl to be
* considered supporting WFS:
*
* 1) ogcServers objects are loaded
* 2) its node `type` property is equal to `WMS`
* 3) in its node `childLayers` property, the `queryable` property is set
* to `true`
* 4) the ogcServer defined in 3) has the `wfsSupport` property set to `true`.
*
* @param {import('ngeo/layertree/Controller').LayertreeController} treeCtrl The layer tree controller
* @returns {?WFSConfig} The configuration object.
*/
EditingSnappingService.prototype.getWFSConfig_ = function (treeCtrl) {
// (1)
if (this.ogcServers_ === null) {
return null;
}
const gmfLayer = /** @type {import('gmf/themes').GmfLayer} */ (treeCtrl.node);
// (2)
if (gmfLayer.type !== ThemeNodeType.WMS) {
return null;
}
const gmfLayerWMS = /** @type {import('gmf/themes').GmfLayerWMS} */ (/** @type {any} */ (gmfLayer));
// (3)
const featureTypes = [];
for (let i = 0, ii = gmfLayerWMS.childLayers.length; i < ii; i++) {
if (gmfLayerWMS.childLayers[i].queryable) {
featureTypes.push(gmfLayerWMS.childLayers[i].name);
}
}
if (!featureTypes.length) {
return null;
}
// (4)
const ogcServer = this.getOGCServer_(treeCtrl);
if (!ogcServer || !ogcServer.wfsSupport) {
return null;
}
// At this point, every requirements have been met.
// Create and return the configuration.
const urlWfs = ogcServer.urlWfs;
if (!urlWfs) {
throw new Error('Missing urlWfs');
}
return {
featureTypes: featureTypes.join(','),
url: urlWfs,
};
};
/**
* @param {import('ngeo/layertree/Controller').LayertreeController} treeCtrl The layer tree controller
* @returns {boolean} True if state is on and snapping is activated for that layer.
*/
EditingSnappingService.prototype.isSnappingActiveForTreeCtrl_ = function (treeCtrl) {
// Note: a snappable treeCtrl can only be a leaf, therefore the only possible
// states are: 'on' and 'off'.
if (treeCtrl.getState() !== 'on') {
return false;
}
if (treeCtrl.properties.snapping !== undefined) {
if (typeof treeCtrl.properties.snapping !== 'boolean') {
throw new Error('Wrong snappingActive type');
}
return treeCtrl.properties.snapping;
}
const node = /** @type {import('gmf/themes').GmfLayer} */ (treeCtrl.node);
const config = getSnappingConfig(node);
return config !== null && config.activated;
};
/**
* @param {import('ngeo/layertree/Controller').LayertreeController} treeCtrl The layer tree controller
* @param {boolean} newVal New value for the layer
*/
EditingSnappingService.prototype.handleTreeCtrlStateChange_ = function (treeCtrl, newVal) {
const uid = olUtilGetUid(treeCtrl);
const item = this.cache_[uid];
newVal ? this.activateItem_(item) : this.deactivateItem_(item);
};
/**
* Activate a cache item by adding a Snap interaction to the map and launch
* the initial request to get the features.
*
* @param {CacheItem} item Cache item.
*/
EditingSnappingService.prototype.activateItem_ = function (item) {
if (!this.map_) {
throw new Error('Missing map');
}
// No need to do anything if item is already active
if (item.active) {
return;
}
const map = this.map_;
const interaction = new CustomSnap({
edge: item.snappingConfig.edge,
features: item.features,
pixelTolerance: item.snappingConfig.tolerance,
vertex: item.snappingConfig.vertex,
});
map.addInteraction(interaction);
item.interaction = interaction;
item.active = true;
// Init features
this.loadItemFeatures_(item);
};
/**
* Deactivate a cache item by removing the snap interaction and clearing any
* existing features.
*
* @param {CacheItem} item Cache item.
*/
EditingSnappingService.prototype.deactivateItem_ = function (item) {
if (!this.map_) {
throw new Error('Missing map');
}
// No need to do anything if item is already inactive
if (!item.active) {
return;
}
const map = this.map_;
const interaction = item.interaction;
if (!interaction) {
throw new Error('Missing interaction');
}
map.removeInteraction(interaction);
item.interaction = null;
item.features.clear();
// If a previous request is still running, cancel it.
if (item.requestDeferred) {
item.requestDeferred.resolve();
item.requestDeferred = null;
}
item.active = false;
this.refreshSnappingSource_();
};
EditingSnappingService.prototype.loadAllItems_ = function () {
this.mapViewChangePromise_ = null;
let item;
for (const uid in this.cache_) {
item = this.cache_[uid];
if (item.active) {
this.loadItemFeatures_(item);
}
}
};
/**
* Manually refresh all features
*/
EditingSnappingService.prototype.refresh = function () {
this.loadAllItems_();
};
/**
* For a specific cache item, issue a new WFS GetFeatures request. The returned
* features set in the item collection of features (they replace any existing
* ones first).
*
* @param {CacheItem} item Cache item.
*/
EditingSnappingService.prototype.loadItemFeatures_ = function (item) {
if (!this.map_) {
throw new Error('Missing map');
}
// If a previous request is still running, cancel it.
if (item.requestDeferred) {
item.requestDeferred.resolve();
}
const map = this.map_;
const view = map.getView();
const size = map.getSize();
if (!size) {
throw new Error('Missing size');
}
const extent = view.calculateExtent(size);
const projCode = view.getProjection().getCode();
const featureTypes = item.wfsConfig.featureTypes.split(',');
const getFeatureOptions = {
srsName: projCode,
featureNS: item.featureNS,
featurePrefix: item.featurePrefix,
featureTypes: featureTypes,
outputFormat: 'GML3',
bbox: extent,
geometryName: DEFAULT_GEOMETRY_NAME,
maxFeatures: item.maxFeatures,
};
const wfsFormat = new olFormatWFS();
const xmlSerializer = new XMLSerializer();
const featureRequestXml = wfsFormat.writeGetFeature(getFeatureOptions);
const featureRequest = xmlSerializer.serializeToString(featureRequestXml);
const url = item.wfsConfig.url;
item.requestDeferred = this.q_.defer();
this.http_
.post(url, featureRequest, {timeout: item.requestDeferred.promise})
.then((response) => {
// (1) Unset requestDeferred
item.requestDeferred = null;
// (2) Clear any previous features in the item
item.features.clear();
// (3) Read features from request response and add them to the item
const readFeatures =
/** @type {import('ol/Feature.js').default<import("ol/geom/Geometry.js").default>[]} */ (
new olFormatWFS().readFeatures(response.data)
);
if (readFeatures) {
item.features.extend(readFeatures);
this.refreshSnappingSource_();
}
})
.catch((err) => {
if (err.xhrStatus === 'abort') {
console.error('WFS request aborted.');
} else {
console.error(err);
}
});
};
/**
* Called when the map view changes. Load all active cache items after a small
* delay. Cancel any currently delayed call, if required.
*/
EditingSnappingService.prototype.handleMapMoveEnd_ = function () {
if (this.mapViewChangePromise_) {
this.timeout_.cancel(this.mapViewChangePromise_);
}
this.mapViewChangePromise_ = this.timeout_(this.loadAllItems_.bind(this), 400);
};
EditingSnappingService.prototype.refreshSnappingSource_ = function () {
if (this.ngeoSnappingSource_ === undefined) {
return;
}
this.ngeoSnappingSource_.clear();
for (const uid in this.cache_) {
const item = this.cache_[uid];
if (item.features === undefined) {
throw new Error('Missing features');
}
if (item.active) {
this.ngeoSnappingSource_.addFeatures(item.features.getArray());
}
}
};
/**
* Called when a File data source is added to the File Group (imported
* geospatial files). Make its features snappable.
*
* @param {Event|import('ol/events/Event').default} evt Event
*/
EditingSnappingService.prototype.handleFileGroupDataSourcesCollectionAdd_ = function (evt) {
if (!(evt instanceof CollectionEvent)) {
return;
}
const fileDataSource = evt.element;
if (!(fileDataSource instanceof ngeoDatasourceFile)) {
return;
}
// (1) Create Snap interaction and give it the features collection
// of the data source.
const features = fileDataSource.featuresCollection;
const gmfSnappingConfig = this.gmfSnappingConfig_;
const interaction = new CustomSnap({
edge: gmfSnappingConfig.edge,
features,
pixelTolerance: gmfSnappingConfig.tolerance,
vertex: gmfSnappingConfig.vertex,
});
// (2) Watch the visible property of the data source. When ON, the
// snap should be added. When OFF, it should be removed.
const visibleWatcherUnregister = this.rootScope_.$watch(() => {
return fileDataSource.visible;
}, this.handleFileDataSourceVisibleChange_.bind(this, fileDataSource));
const uid = olUtilGetUid(fileDataSource);
// (3) Create and add the cache item
this.cacheFileDataSource_[uid] = {
active: false,
fileDataSource,
interaction,
visibleWatcherUnregister,
};
// (4) Initialize the Snap interaction with the File DataSource,
// depending on its current visible value
this.handleFileDataSourceVisibleChange_(fileDataSource);
};
/**
* Called when a File data source is removed from the File
* Group. Remove the features from being snappable.
*
* @param {Event|import('ol/events/Event').default} evt Event
*/
EditingSnappingService.prototype.handleFileGroupDataSourcesCollectionRemove_ = function (evt) {
if (!(evt instanceof CollectionEvent)) {
return;
}
const fileDataSource = evt.element;
if (!(fileDataSource instanceof ngeoDatasourceFile)) {
return;
}
const uid = olUtilGetUid(fileDataSource);
if (!this.cacheFileDataSource_[uid]) {
return;
}
const item = this.cacheFileDataSource_[uid];
const map = this.map_;
// (1) Unregister watcher
item.visibleWatcherUnregister();
// (2) Remove snap interaction, if item is active
if (item.active) {
map.removeInteraction(item.interaction);
}
// (3) Delete item from cache, and we're done
delete this.cacheFileDataSource_[uid];
};
/**
* Called when the "visible" property of a File data source
* changes. Add or remove the Snap interaction for that data source
* depending on the property value.
*
* @param {ngeoDatasourceFile} fileDataSource
*/
EditingSnappingService.prototype.handleFileDataSourceVisibleChange_ = function (fileDataSource) {
const uid = olUtilGetUid(fileDataSource);
const item = this.cacheFileDataSource_[uid];
const visible = fileDataSource.visible;
// No need to do anything if DS visible/hidden and the item is
// active/inactive already.
if (item.active === visible) {
return;
}
item.active = visible;
const map = this.map_;
if (visible) {
map.addInteraction(item.interaction);
} else {
map.removeInteraction(item.interaction);
}
};
/**
* @typedef {Object<string, CacheItem>} Cache
*/
/**
* @typedef {Object} CacheItem
* @property {boolean} active
* @property {string} featureNS
* @property {string} featurePrefix
* @property {import('ol/Collection').default<import('ol/Feature').default<import('ol/geom/Geometry').default>>} features
* @property {?import('ol/interaction/Snap').default} interaction
* @property {number} maxFeatures
* @property {?angular.IDeferred<unknown>} requestDeferred
* @property {import('gmf/themes').GmfSnappingConfig} snappingConfig
* @property {Function} stateWatcherUnregister
* @property {import('ngeo/layertree/Controller').LayertreeController} treeCtrl
* @property {WFSConfig} wfsConfig
*/
/**
* The key is: A uid string generated from the fileDataSource
*
* @typedef {Object<string, CacheFileDataSourceItem>} CacheFileDataSource
*/
/**
* @typedef {Object} CacheFileDataSourceItem
* @property {boolean} active
* @property {import('ngeo/datasource/File').default} fileDataSource
* @property {import('ol/interaction/Snap').default} interaction
* @property {Function} visibleWatcherUnregister
*/
/**
* @typedef {Object} WFSConfig
* @property {string} featureTypes
* @property {string} url
*/
/**
* @type {angular.IModule}
* @hidden
*/
const myModule = angular.module('gmfSnapping', [
gmfDatasourceFileGroup.name,
gmfLayertreeTreeManager.name,
gmfThemeThemes.name,
ngeoLayertreeController.name,
]);
myModule.service('gmfSnapping', EditingSnappingService);
export default myModule;