-
Notifications
You must be signed in to change notification settings - Fork 60
/
index.js
1533 lines (1341 loc) · 56.7 KB
/
index.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
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-present Dan "Ducky" Little
*
* 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.
*/
/** The big bopper of all the GeoMoose Components, the Catalog.
*
* This is the most exercised component of GeoMoose and serves
* as the 'dispatch' center to the map, presenting the layers
* of the mapbook in a nice tree format.
*/
import React from 'react';
import { connect } from 'react-redux';
import ReactResizeDetector from 'react-resize-detector';
import { withTranslation } from 'react-i18next';
import uuid from 'uuid';
import md5 from 'md5/md5';
import * as mapSourceActions from '../../actions/mapSource';
import * as mapActions from '../../actions/map';
import {removeFeature, setEditFeature} from '../../actions/edit';
import * as util from '../../util';
import * as jsts from '../../jsts';
import GeoJSONFormat from 'ol/format/GeoJSON';
import EsriJSONFormat from 'ol/format/EsriJSON';
import GML2Format from 'ol/format/GML2';
import WMSGetFeatureInfoFormat from 'ol/format/WMSGetFeatureInfo';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import * as proj from 'ol/proj';
import olScaleLine from 'ol/control/ScaleLine';
import olView from 'ol/View';
import olMap from 'ol/Map';
import * as olXml from 'ol/xml';
import olCollection from 'ol/Collection';
import olSelectInteraction from 'ol/interaction/Select';
import olDrawInteraction, {createBox} from 'ol/interaction/Draw';
import olModifyInteraction from 'ol/interaction/Modify';
import * as olEventConditions from 'ol/events/condition';
import olRotateControl from 'ol/control/Rotate';
/* Import the various layer types */
import * as wmsLayer from './layers/wms';
import * as xyzLayer from './layers/xyz';
import * as agsLayer from './layers/ags';
import * as vectorLayer from './layers/vector';
import * as bingLayer from './layers/bing';
import * as usngLayer from './layers/usng';
import {createLayer as createBlankLayer} from './layers/blank';
import { buildWfsQuery, wfsGetFeatures} from './layers/wfs';
import {EDIT_LAYER_NAME} from '../../defaults';
import EditorModal from '../editor';
import RemoveModal from '../editor/remove-modal';
import AttributionDisplay from './attribution-display';
import JumpToZoom from './jump-to-zoom';
import ContextControls from './context-controls';
function getControls(mapConfig) {
const controls = [];
if (mapConfig.allowRotate !== false) {
controls.push(new olRotateControl());
}
const scaleLineConf = Object.assign({enabled: false, units: 'metric'}, mapConfig.scaleLine);
if (scaleLineConf.enabled !== false) {
controls.push(new olScaleLine({units: scaleLineConf.units}));
}
return controls;
}
const GEOJSON_FORMAT = new GeoJSONFormat();
const getPixelTolerance = (querySource, defaultPx = 10) => {
// the default pixel tolerance is 10 pixels.
let pxTolerance = defaultPx;
try {
if (querySource.config['pixel-tolerance']) {
pxTolerance = parseFloat(querySource.config['pixel-tolerance']);
}
} catch (err) {
// swallow the error
}
return pxTolerance;
};
const applyPixelTolerance = (queryFeature, querySource, resolution, defaultPxTolerance) => {
const pxTolerance = getPixelTolerance(querySource, defaultPxTolerance);
if (pxTolerance > 0 && queryFeature.geometry.type === 'Point') {
// buffer point is in pixels,
// this converts pixels to ground units
const width = pxTolerance * resolution;
return util.getSquareBuffer(
queryFeature.geometry.coordinates,
width
);
}
return queryFeature;
};
class Map extends React.Component {
constructor() {
super();
// hash of mapsources
this.olLayers = { };
// the current 'active' interaction
this.currentInteraction = null;
// a hash of interval timers for layers that
// are set to auto-refresh
this.intervals = {};
this.updateMapSize = this.updateMapSize.bind(this);
// this is used when a feature isn't finished yet.
this.sketchFeature = null;
}
/** Update a source's important bits.
*
* @param sourceName The name of the mapsource to update.
*
*/
updateSource(sourceName) {
const map_source = this.props.mapSources[sourceName];
const ol_layer = this.olLayers[sourceName];
switch(map_source.type) {
case 'wms' :
wmsLayer.updateLayer(this.map, ol_layer, map_source);
break;
case 'xyz' :
xyzLayer.updateLayer(this.map, ol_layer, map_source);
break;
case 'ags' :
agsLayer.updateLayer(this.map, ol_layer, map_source);
break;
case 'vector' :
case 'wfs' :
case 'ags-vector':
case 'geojson':
vectorLayer.updateLayer(
this.map,
ol_layer,
map_source,
this.props.mapView.interactionType
);
break;
case 'bing':
bingLayer.updateLayer(this.map, ol_layer, map_source);
break;
case 'usng':
usngLayer.updateLayer(this.map, ol_layer, map_source);
break;
case 'blank':
// this is a non-op, blank will be blank for all time.
break;
default:
console.info('Unhandled map-source type: ' + map_source.type);
}
}
/** Create an OL Layers based on a GM MapSource definition
*
* @param mapSource
*
* @returns OpenLayers Layer with its source set.
*/
createLayer(mapSource) {
switch(mapSource.type) {
case 'wms':
return wmsLayer.createLayer(mapSource);
case 'xyz':
return xyzLayer.createLayer(mapSource);
case 'ags':
return agsLayer.createLayer(mapSource);
case 'vector':
case 'wfs':
case 'ags-vector':
case 'geojson':
return vectorLayer.createLayer(mapSource);
case 'bing':
return bingLayer.createLayer(mapSource);
case 'usng':
return usngLayer.createLayer(mapSource);
case 'blank':
return createBlankLayer();
default:
throw new Error('Unhandled creation of map-source type: ' + mapSource.type);
}
}
/** Make a WMS GetFeatureInfo query
*
* @param queryId The query id.
* @param selection The selection section of the query.
* @param queryLayer The name of the layer being queried.
*
*/
wmsGetFeatureInfoQuery(queryId, selection, queryLayer) {
const map_projection = this.map.getView().getProjection();
const view = this.props.mapView;
// get the map source
const ms_name = util.getMapSourceName(queryLayer);
const fail_layer = (message) => {
// dispatch a message that the query has failed.
this.props.store.dispatch(
// true for 'failed', empty array to prevent looping side-effects.
mapActions.resultsForQuery(queryId, queryLayer, true, [], message)
);
// TODO: This delay allows the state tree to refresh before
// checking for completeness.
setTimeout(() => {
this.checkQueryForCompleteness(queryId, queryLayer);
}, 200);
};
const selectionPoints = selection.filter(feature =>
feature.geometry && feature.geometry.type === 'Point');
// check that we have a geometry, if not fail.
if (selectionPoints.length === 0) {
// set the failure
fail_layer('No valid selection geometry.');
// leave the function.
return;
}
const coords = selectionPoints[0].geometry.coordinates;
const src = this.olLayers[ms_name].getSource();
// TODO: Allow the configuration to specify GML vs GeoJSON,
// but GeoMoose needs a real feature returned.
const params = {
'FEATURE_COUNT': 1000,
'QUERY_LAYERS': util.getLayerName(queryLayer),
'INFO_FORMAT': 'application/vnd.ogc.gml'
};
const info_url = src.getFeatureInfoUrl(coords, view.resolution, map_projection.getCode(), params);
fetch(info_url, {
headers: {
'Access-Control-Request-Headers': '*',
},
})
.then(r => r.text())
.then(responseText => {
// not all WMS services play nice and will return the
// error message as a 200, so this still needs checked.
if(responseText) {
const gml_format = new WMSGetFeatureInfoFormat();
const features = gml_format.readFeatures(responseText);
const js_features = GEOJSON_FORMAT.writeFeaturesObject(features).features;
this.props.store.dispatch(
mapActions.resultsForQuery(queryId, queryLayer, false, js_features)
);
} else {
fail_layer();
}
this.checkQueryForCompleteness(queryId, queryLayer);
})
.catch((err, msg) => {
fail_layer();
this.checkQueryForCompleteness(queryId, queryLayer);
});
}
/** Iterate through the layers and ensure that they have all
* been completed. The state may not have been updated yet,
* so if a layer has been recently completed then 'completedLayer'
* is passed in to assume it has been populated despite what the state
* says.
*
* @param queryId The id of the query to check for completeness.
* @param completedLayer The path of a layer which has been recently completed.
*
* @returns Nothing, dispatches a finishQuery action if all layers have been completed.
*/
checkQueryForCompleteness(queryId, completedLayer) {
const query = this.props.queries[queryId];
let all_completed = true;
// check to see if there are results for all the layers.
if(query && query.layers) {
for(const layer of query.layers) {
all_completed = all_completed && (query.results[layer] || (layer === completedLayer));
}
} else if (query && query.layers.length > 0) {
all_completed = false;
}
if(all_completed) {
if (query.runOptions && query.runOptions.zoomToResults) {
this.props.zoomToResults(query);
}
this.props.store.dispatch(mapActions.finishQuery(queryId));
}
}
/** Create a WFS formatted query and send it
*
* @param queryId
* @param query
*
*/
wfsGetFeatureQuery(queryId, query, queryLayer) {
const map_projection = this.map.getView().getProjection();
// get the map source
const ms_name = util.getMapSourceName(queryLayer);
const map_source = this.props.mapSources[ms_name];
// the internal storage mechanism requires features
// returned from the query be stored in 4326 and then
// reprojected on render.
let query_projection = map_projection;
if(map_source.wgs84Hack) {
query_projection = new proj.get('EPSG:4326');
}
let ol_layer = this.olLayers[ms_name];
if(!ol_layer) {
ol_layer = this.createLayer(map_source);
}
// check for the output_format based on the params
let output_format = 'text/xml; subtype=gml/2.1.2';
if(map_source.params.outputFormat) {
output_format = map_source.params.outputFormat;
}
if (query.selection && query.selection.length === 1) {
query.selection[0] = applyPixelTolerance(
query.selection[0], map_source,
this.props.mapView.resolution, 10);
}
const wfs_query_xml = buildWfsQuery(query, map_source, map_projection, output_format);
// Ensure all the extra URL params are attached to the
// layer.
const wfs_url = map_source.urls[0] + '?' + util.formatUrlParameters(map_source.params);
const is_json_like = (output_format.toLowerCase().indexOf('json') > 0);
fetch(wfs_url, {
method: 'POST',
body: wfs_query_xml,
headers: {
'Access-Control-Request-Headers': '*',
},
})
.then(r => r.text())
.then(response => {
if(response) {
// check for a WFS error message
if(response.search(/(ows|wfs):exception/i) >= 0) {
// parse the document.
const wfs_doc = olXml.parse(response);
const tags = ['ows:ExceptionText', 'wfs:ExceptionText'];
let error_text = '';
for(let t = 0, tt = tags.length; t < tt; t++) {
const nodes = wfs_doc.getElementsByTagName(tags[t]);
for(let n = 0, nn = nodes.length; n < nn; n++) {
error_text += olXml.getAllTextContent(nodes[n]) + '\n';
}
}
// ensure that the console variable exists
if(typeof console !== undefined) {
console.error(error_text);
}
// dispatch an error status.
this.props.store.dispatch(
mapActions.resultsForQuery(queryId, queryLayer, true, [], error_text)
);
} else {
// place holder for features to be added.
let js_features = [];
if(is_json_like) {
js_features = JSON.parse(response).features;
} else {
const gml_format = new GML2Format();
const features = gml_format.readFeatures(response, {
featureProjection: map_projection,
dataProjection: query_projection
});
// be ready with some json.
const json_format = new GeoJSONFormat();
// create the features array.
for(const feature of features) {
// feature to JSON.
const js_feature = json_format.writeFeatureObject(feature);
// ensure that every feature has a "boundedBy" attribute.
js_feature.properties.boundedBy = feature.getGeometry().getExtent();
// add it to the stack.
js_features.push(js_feature);
}
}
// apply the transforms
js_features = util.transformFeatures(map_source.transforms, js_features);
this.props.store.dispatch(
mapActions.resultsForQuery(queryId, queryLayer, false, js_features)
);
}
}
this.checkQueryForCompleteness(queryId, queryLayer);
})
.catch(() => {
// dispatch a message that the query has failed.
this.props.store.dispatch(
// true for 'failed', empty array to prevent looping side-effects.
mapActions.resultsForQuery(queryId, queryLayer, true, [], 'Server error. Check network logs.')
);
this.checkQueryForCompleteness(queryId, queryLayer);
});
}
/** Create a FeatureService formatted query and send it
*
* @param queryId
* @param query
*
*/
agsFeatureQuery(queryId, query, queryLayer) {
// get the map source
const ms_name = util.getMapSourceName(queryLayer);
const map_source = this.props.mapSources[ms_name];
// if the openlayers layer is not on, this fakes
// one for use in the query.
let ol_layer = this.olLayers[ms_name];
if(!ol_layer) {
ol_layer = this.createLayer(map_source);
}
const fix_like = function(value) {
const new_value = value.replace('*', '%');
return new_value;
};
const simple_op = function(op, name, value) {
if(typeof(value) === 'number') {
return name + ' ' + op + ' ' + value;
} else {
return `${name} ${op} '${value}'`;
}
};
// map the functions from OpenLayers to the internal
// types
const filter_mapping = {
'like': function(name, value) {
return name + ' like \'' + fix_like(value) + '\'';
},
'ilike': function(name, value) {
return 'upper(' + name + ') like upper(\'' + fix_like(value) + '\')';
},
'eq': function(name, value) {
return simple_op('=', name, value);
},
'ge': function(name, value) {
return simple_op('>=', name, value);
},
'gt': function(name, value) {
return simple_op('>', name, value);
},
'le': function(name, value) {
return simple_op('<=', name, value);
},
'lt': function(name, value) {
return simple_op('<', name, value);
},
};
// setup the necessary format converters.
const esri_format = new EsriJSONFormat();
const query_params = {
f: 'json',
returnGeometry: 'true',
spatialReference: JSON.stringify({
wkid: 102100
}),
inSR: 102100, outSR: 102100,
outFields: '*',
};
if (query.selection && query.selection.length > 0) {
const queryFeature = applyPixelTolerance(
query.selection[0], map_source,
this.props.mapView.resolution, 2);
const queryGeometry = queryFeature.geometry;
// make this an E**I geometry.
const ol_geom = GEOJSON_FORMAT.readGeometry(queryGeometry);
// translate the geometry to E**I-ish
const geom_type_lookup = {
'Point': 'esriGeometryPoint',
'MultiPoint': 'esriGeometryMultipoint',
'LineString': 'esriGeometryPolyline',
'Polygon': 'esriGeometryPolygon',
};
// setup the spatial filter.
query_params.geometryType = geom_type_lookup[queryGeometry.type];
query_params.geometry = esri_format.writeGeometry(ol_geom);
query_params.spatialRel = 'esriSpatialRelIntersects';
// for lines?:'esriSpatialRelEnvelopeIntersects';
}
// build the filter fields.
const where_statements = [];
for(const filter of query.fields) {
where_statements.push(filter_mapping[filter.comparitor](filter.name, filter.value));
}
query_params.where = where_statements.join(' and ');
const params = Object.assign({}, query_params, map_source.params);
// get the query service url.
const query_url = map_source.urls[0] + '/query/';
util.xhr({
url: query_url,
method: 'get',
type: 'jsonp',
data: params,
success: (response) => {
// not all WMS services play nice and will return the
// error message as a 200, so this still needs checked.
if(response) {
if (response.error && response.error.code !== 200){
console.error(response.error);
this.props.store.dispatch(
// true for 'failed', empty array to prevent looping side-effects.
mapActions.resultsForQuery(queryId, queryLayer, true, [])
);
} else {
// convert the esri features to OL features.
const features = esri_format.readFeatures(response);
// be ready with some json.
const json_format = new GeoJSONFormat();
// create the features array.
let js_features = [];
for(const feature of features) {
// feature to JSON.
const js_feature = json_format.writeFeatureObject(feature);
// ensure that every feature has a "boundedBy" attribute.
js_feature.properties.boundedBy = feature.getGeometry().getExtent();
// add it to the stack.
js_features.push(js_feature);
}
// apply the transforms
js_features = util.transformFeatures(map_source.transforms, js_features);
this.props.store.dispatch(
mapActions.resultsForQuery(queryId, queryLayer, false, js_features)
);
}
}
},
error: () => {
// dispatch a message that the query has failed.
this.props.store.dispatch(
// true for 'failed', empty array to prevent looping side-effects.
mapActions.resultsForQuery(queryId, queryLayer, true, [])
);
},
complete: () => {
this.checkQueryForCompleteness(queryId, queryLayer);
}
});
}
/** Run a query in memory.
*
*/
vectorLayerQuery(queryId, query, queryLayer) {
// get the map source
const ms_name = util.getMapSourceName(queryLayer);
const map_source = this.props.mapSources[ms_name];
// if the openlayers layer is not on, this fakes
// one for use in the query.
let ol_layer = this.olLayers[ms_name];
if(!ol_layer) {
ol_layer = this.createLayer(map_source);
}
// get the src
const src = ol_layer.getSource();
const format = new GeoJSONFormat();
const result_features = [];
const selection = query.selection ? query.selection[0] : null;
if(selection && selection.geometry && selection.geometry.type === 'Point') {
const coords = selection.geometry.coordinates;
src.forEachFeatureAtCoordinateDirect(coords, (feature) => {
const jsonFeature = format.writeFeatureObject(feature);
// the temp drawing feature has features set as null
if (jsonFeature.properties !== null) {
result_features.push(jsonFeature);
}
});
}
this.props.store.dispatch(
mapActions.resultsForQuery(queryId, queryLayer, false, result_features)
);
this.checkQueryForCompleteness(queryId, queryLayer);
}
/** Execute a query
*
* @param query
*
*/
runQuery(queries, queryId) {
const query = queries[queryId];
if (!query.layers || query.layers.length === 0) {
// a ha! no layers in the query. consider it done.
this.props.finishQuery(queryId);
}
for(const query_layer of query.layers) {
// get the map source
const ms_name = util.getMapSourceName(query_layer);
const map_source = this.props.mapSources[ms_name];
// Run the appropriate query function
// based on the map-source type
switch(map_source.type) {
case 'wms':
this.wmsGetFeatureInfoQuery(queryId, query.selection, query_layer);
break;
case 'wfs':
this.wfsGetFeatureQuery(queryId, query, query_layer);
break;
case 'ags-vector':
this.agsFeatureQuery(queryId, query, query_layer);
break;
case 'geojson':
case 'vector':
this.vectorLayerQuery(queryId, query, query_layer);
break;
default:
// pass.
}
}
}
/** iterates through the queries and executes
* any query with a 'progress=new' state.
*
* @param Queries Array of query ids.
*/
checkQueries(queries) {
for(const query_id in queries) {
const query = queries[query_id];
if(query && query.progress === 'new') {
// issue a 'started' modification so the query is
// not run twice.
this.props.store.dispatch(mapActions.startQuery(query_id));
// run the query.
this.runQuery(queries, query_id);
}
}
if(queries.order.length > 0) {
const query_id = queries.order[0];
const query = queries[query_id];
if(query.progress === 'finished') {
// check the filters
const filter_json = JSON.stringify(query.filter);
const filter_md5 = md5(filter_json);
if(this.currentQueryId !== query_id
|| this.currentQueryFilter !== filter_md5) {
this.renderQueryLayer(query);
this.currentQueryId = query_id;
this.currentQueryFilter = filter_md5;
}
}
} else {
// once there are no more queries,
// clear the results from the map.
const results = this.props.mapSources.results;
if(results && results.features && results.features.length > 0) {
this.props.store.dispatch(mapSourceActions.clearFeatures('results', 'results'));
}
}
}
/** Remove an interval to prevent a layer from being repeatedly
* refreshed.
*
* @param {String} msName The name of the map-source with refresh enabled.
*
*/
removeRefreshInterval(msName) {
if(this.intervals[msName]) {
clearInterval(this.intervals[msName]);
delete this.intervals[msName];
}
}
/** Forces a layer to refresh.
*
*/
refreshLayer(mapSource) {
switch(mapSource.type) {
case 'wms':
const wms_src = this.olLayers[mapSource.name].getSource();
const params = wms_src.getParams();
// ".ck" = "cache killer"
params['.ck'] = uuid.v4();
wms_src.updateParams(params);
break;
default:
// do nothing
}
}
/** Create an interval that will refresh the layer's contents.
*
*/
createRefreshInterval(mapSource) {
// prevent the creation of a pile of intervals
if(!this.intervals.hasOwnProperty(mapSource.name)) {
// refresh is stored in seconds, multiplying by 1000
// converts ito the milliseconds expected by setInterval.
this.intervals[mapSource.name] = setInterval(() => {
this.refreshLayer(mapSource);
}, mapSource.refresh * 1000);
}
}
/* Render the query as a layer.
*
*/
renderQueryLayer(query) {
if(this.props.mapSources.results) {
// clear the features
this.props.store.dispatch(mapSourceActions.clearFeatures('results', 'results'));
let features = [];
for (const layer_path in query.results) {
// ensure the layer_path does not have a failure.
if(query.results[layer_path].failed !== true) {
// get the features, after applying the query filter
features = features.concat(util.matchFeatures(query.results[layer_path], query.filter));
}
}
// render the features from all the layers
this.props.store.dispatch(mapSourceActions.addFeatures('results', features));
} else {
console.error('No "results" layer has been defined, cannot do smart query rendering.');
}
}
/** Refresh the map-sources in the map
*
*/
refreshMapSources() {
// get the list of current active map-sources
const print_only = (this.props.printOnly === true);
const active_map_sources = mapSourceActions.getActiveMapSources(this.props.mapSources, print_only);
// annoying O(n^2) iteration to see if the mapsource needs
// to be turned off.
for(const ms_name in this.olLayers) {
// if the ms_name is not active, turn the entire source off.
if(active_map_sources.indexOf(ms_name) < 0) {
this.olLayers[ms_name].setVisible(false);
this.removeRefreshInterval(ms_name);
}
}
// for each one of the active mapsources,
// determine if the olSource already exists, if not
// create it, if it does, turn it back on.
for(const ms_name of active_map_sources) {
const map_source = this.props.mapSources[ms_name];
if(!this.olLayers[ms_name]) {
// create the OL layer
this.olLayers[ms_name] = this.createLayer(map_source);
this.map.addLayer(this.olLayers[ms_name]);
} else {
this.updateSource(ms_name);
this.olLayers[ms_name].setVisible(true);
}
this.olLayers[ms_name].setZIndex(map_source.zIndex);
this.olLayers[ms_name].setOpacity(map_source.opacity);
// if there is a refresh interval set then
// create an interval which refreshes the
// layer.
if(map_source.refresh !== null) {
// here's hoping this is an integer,
// thanks Javascript!
this.createRefreshInterval(map_source);
} else if(map_source.refresh === null && this.intervals[ms_name]) {
this.removeRefreshInterval(ms_name);
}
}
}
/** Add features to the selection layer.
*
* @param inFeatures Current list of features
* @param inBuffer A buffer distance to apply.
*
*/
addSelectionFeatures(inFeatures, inBuffer) {
const features = inFeatures
.map(feature => GEOJSON_FORMAT.writeFeatureObject(feature));
const buffer = inBuffer !== 0 && !isNaN(inBuffer) ? inBuffer : 0;
let bufferedFeature = features;
if (buffer !== 0) {
// buffer + union the features
const wgs84Features = util.projectFeatures(features, 'EPSG:3857', 'EPSG:4326');
// buffer those features.
bufferedFeature =
[jsts.union(util.projectFeatures(
wgs84Features.map(feature => {
const buffered = jsts.bufferFeature(feature, buffer);
buffered.properties = {
buffer: true,
};
return buffered;
}),
'EPSG:4326',
'EPSG:3857'
)
), ];
}
// the selection feature(s) are the original, as-drawn feature.
this.props.setSelectionFeatures(features);
// the feature(s) stored in the selection are what will
// be used for querying.
this.props.setFeatures('selection', bufferedFeature);
}
/** Create a selection layer for temporary selection features.
*
*/
configureSelectionLayer() {
const src_selection = new VectorSource();
this.selectionLayer = new VectorLayer({
source: src_selection,
});
// Fake a GeoMoose style source + layer definition
// to bootstrap the style
vectorLayer.applyStyle(this.selectionLayer, {
layers: [
{on: true, style: this.props.selectionStyle},
],
});
}
/** This is called after the first render.
* As state changes will not actually change the DOM according to
* React, this will establish the map.
*/
componentDidMount() {
// create the selection layer.
this.configureSelectionLayer();
const view_params = {};
if(this.props.center) {
view_params.center = this.props.center
// check for a z-settings.
if(this.props.zoom) {
view_params.zoom = this.props.zoom;
} else if(this.props.resolution) {
view_params.resolution = this.props.resolution;
}
} else {
view_params.center = this.props.mapView.center;
if(this.props.mapView.zoom) {
view_params.zoom = this.props.mapView.zoom;
} else {
view_params.resolution = this.props.mapView.resolution;
}
}
if (this.props.config.view) {
const mixinKeys = ['extent', 'center', 'zoom', 'maxZoom', 'minZoom'];
mixinKeys.forEach(key => {
if (this.props.config.view[key]) {
view_params[key] = this.props.config.view[key];
}
});
}
// initialize the map.
this.map = new olMap({
target: this.mapDiv,
layers: [this.selectionLayer, ],
logo: false,
view: new olView(view_params),
controls: getControls(this.props.config),
});
if (this.props.mapView.extent) {
this.zoomToExtent(this.props.mapView.extent);
}
// when the map moves, dispatch an action
this.map.on('moveend', () => {
// get the view of the map
const view = this.map.getView();
// create a "mapAction" and dispatch it.
this.props.store.dispatch(mapActions.setView({
center: view.getCenter(),
resolution: view.getResolution(),
zoom: view.getZoom()
}));
});
// and when the cursor moves, dispatch an action
// there as well.
this.map.on('pointermove', (event) => {
const action = mapActions.cursor(event.coordinate);
this.props.store.dispatch(action);
if(this.sketchFeature) {
// convert the sketch feature's geometry to JSON and kick it out
// to the store.
const json_geom = util.geomToJson(this.sketchFeature.getGeometry());
this.props.store.dispatch(mapActions.updateSketchGeometry(json_geom));
}
});
// call back for when the map has finished rendering.