-
Notifications
You must be signed in to change notification settings - Fork 31
/
QGISExtensions.js
executable file
·1861 lines (1666 loc) · 71 KB
/
QGISExtensions.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
/*
*
* QGISExtensions.js -- part of QGIS Web Client
*
* Copyright (2010-2012), The QGIS Project All rights reserved.
* QGIS Web Client is released under a BSD license. Please see
* https://github.com/qgis/qgis-web-client/blob/master/README
* for the full text of the license and the list of contributors.
*
*/
/* QGIS extensions:
* QGIS.WMSCapabilitiesLoader
* QGIS.PrintProvider
* QGIS.SearchComboBox
* QGIS.SearchPanel
* QGIS.FeatureInfoParser
* QGIS.LayerOrderPanel
*/
//new namespace for QGIS extensions
//do not modify those three lines
if (!window.QGIS) {
window.QGIS = {};
}
/* ************************** QGIS.WMSCapabilitiesLoader ************************** */
// parse GetProjectSettings from QGIS Mapserver
// extends GeoExt.tree.WMSCapabilitiesLoader in order to expose the WMSCapabilities Tree to later read out settings from the tree
QGIS.WMSCapabilitiesLoader = function(config) {
Ext.apply(this, config);
QGIS.WMSCapabilitiesLoader.superclass.constructor.call(this,config);
};
Ext.extend(QGIS.WMSCapabilitiesLoader, GeoExt.tree.WMSCapabilitiesLoader, {
useGetProjectSettings: true,
WMSCapabilities: null,
projectSettings: null,
//this list holds layer properties, indexed by layername
layerProperties: [],
//this list holds a mapping between title and layer name - the tree shows the title, the WMS requests need names
layerTitleNameMapping: [],
initialVisibleLayers: [],
getParams: function(node) {
return {
SERVICE: 'WMS',
VERSION: '1.3.0',
REQUEST: this.useGetProjectSettings ? 'GetProjectSettings' : 'GetCapabilities'
};
},
processResponse : function(response, node, callback, scope) {
if (response.responseXML) {
this.WMSCapabilities = response.responseXML;
}
else {
if (window.DOMParser) {
var parser=new DOMParser();
this.WMSCapabilities=parser.parseFromString(response.responseText,"text/xml");
}
else { // Internet Explorer
this.WMSCapabilities=new ActiveXObject("Microsoft.XMLDOM");
this.WMSCapabilities.async="false";
this.WMSCapabilities.loadXML(response.responseText);
}
}
this.projectSettings = new OpenLayers.Format.WMSCapabilities({
readers: {
"wms": OpenLayers.Util.applyDefaults({
"ComposerTemplates": function(node, obj) {
obj.composerTemplates = [];
this.readChildNodes(node, obj.composerTemplates);
},
"ComposerTemplate": function(node, obj) {
var composerTemplate = {
name: node.getAttribute("name"),
width: parseInt(node.getAttribute("width")),
height: parseInt(node.getAttribute("height"))
};
this.readChildNodes(node, composerTemplate);
obj.push(composerTemplate);
},
"ComposerMap": function(node, obj) {
obj.map = {
name: node.getAttribute("name"),
width: parseInt(node.getAttribute("width")),
height: parseInt(node.getAttribute("height"))
};
},
"ExclusiveLayerGroups": function(node, obj) {
obj.exclusiveLayerGroups = [];
this.readChildNodes(node, obj.exclusiveLayerGroups);
},
"group": function(node, obj) {
// comma separated layer names
obj.push(this.getChildValue(node).split(','));
},
"LayerDrawingOrder": function(node, obj) {
obj.layerDrawingOrder = this.getChildValue(node).split(',');
},
// based on OpenLayers.Format.WMSCapabilities.v1 parser
"Layer": function(node, obj) {
var parentLayer, capability;
if (obj.capability) {
//QGIS Server 3.4.3 can have blank title and name, probably bug, workaround
if(obj.title == undefined) {
obj.title = projectData.project;
}
if(obj.name == undefined) {
obj.name = projectData.project;
}
capability = obj.capability;
parentLayer = obj;
} else {
capability = obj;
}
var attrNode = node.getAttributeNode("queryable");
var queryable = (attrNode && attrNode.specified) ?
node.getAttribute("queryable") : null;
attrNode = node.getAttributeNode("cascaded");
var cascaded = (attrNode && attrNode.specified) ?
node.getAttribute("cascaded") : null;
attrNode = node.getAttributeNode("opaque");
var opaque = (attrNode && attrNode.specified) ?
node.getAttribute('opaque') : null;
// QGIS custom attributes
attrNode = node.getAttributeNode("visible");
var visible = (attrNode && attrNode.specified) ?
node.getAttribute("visible") : null;
var displayField = node.getAttribute('displayField');
attrNode = node.getAttributeNode("checkbox");
var showCheckbox = (attrNode && attrNode.specified) ?
node.getAttribute("checkbox") : null;
attrNode = node.getAttributeNode("legend");
var showLegend = (attrNode && attrNode.specified) ?
node.getAttribute("legend") : null;
attrNode = node.getAttributeNode("metadata");
var showMetadata = (attrNode && attrNode.specified) ?
node.getAttribute("metadata") : null;
var noSubsets = node.getAttribute('noSubsets');
var fixedWidth = node.getAttribute('fixedWidth');
var fixedHeight = node.getAttribute('fixedHeight');
var parent = parentLayer || {},
extend = OpenLayers.Util.extend;
var layer = {nestedLayers: [],
styles: parentLayer ? [].concat(parentLayer.styles) : [],
srs: parentLayer ? extend({}, parent.srs) : {},
metadataURLs: [],
bbox: parentLayer ? extend({}, parent.bbox) : {},
llbbox: parent.llbbox,
dimensions: parentLayer ? extend({}, parent.dimensions) : {},
authorityURLs: parentLayer ? extend({}, parent.authorityURLs) : {},
identifiers: {},
keywords: [],
queryable: (queryable && queryable !== "") ?
(queryable === "1" || queryable === "true" ) :
(parent.queryable || false),
cascaded: (cascaded !== null) ? parseInt(cascaded) :
(parent.cascaded || 0),
opaque: opaque ?
(opaque === "1" || opaque === "true" ) :
(parent.opaque || false),
// QGIS extensions
visible: (visible && visible !== "") ? ( visible === "1" || visible === "true" ) : true,
displayField: displayField,
showCheckbox: (showCheckbox && showCheckbox !== "") ?
( showCheckbox === "1" || showCheckbox === "true" ) : true,
showLegend: (showLegend && showLegend !== "") ?
( showLegend === "1" || showLegend === "true" ) : true,
showMetadata: (showMetadata && showMetadata !== "") ?
( showMetadata === "1" || showMetadata === "true" ) : true,
noSubsets: (noSubsets !== null) ?
(noSubsets === "1" || noSubsets === "true" ) :
(parent.noSubsets || false),
fixedWidth: (fixedWidth != null) ?
parseInt(fixedWidth) : (parent.fixedWidth || 0),
fixedHeight: (fixedHeight != null) ?
parseInt(fixedHeight) : (parent.fixedHeight || 0),
minScale: parent.minScale,
maxScale: parent.maxScale,
attribution: parent.attribution
};
layer.capability = capability;
this.readChildNodes(node, layer);
delete layer.capability;
obj.nestedLayers.push(layer);
if(layer.name) {
var parts = layer.name.split(":"),
request = capability.request,
gfi = request.getfeatureinfo;
if(parts.length > 0) {
layer.prefix = parts[0];
}
capability.layers.push(layer);
if (layer.formats === undefined) {
layer.formats = request.getmap.formats;
}
if (layer.infoFormats === undefined && gfi) {
layer.infoFormats = gfi.formats;
}
}
},
"Attributes": function(node, obj) {
obj.attributes = [];
this.readChildNodes(node, obj.attributes);
},
"Attribute": function(node, obj) {
var attribute = {
name: validateFieldName(node.getAttribute("name")),
alias: node.getAttribute("alias"),
type: node.getAttribute("type"),
precision: parseInt(node.getAttribute("precision")),
length: parseInt(node.getAttribute("length")),
editType: node.getAttribute("editType"),
comment: node.getAttribute("comment")
};
obj.push(attribute);
},
"SRS": function(node, obj) {
obj.srs[this.getChildValue(node)] = true;
}
}, OpenLayers.Format.WMSCapabilities.v1_3.prototype.readers["wms"])
}
}).read(this.WMSCapabilities);
this.processLayer(this.projectSettings.capability, this.projectSettings.capability.request.getmap.href, node);
//fill the list of layer properties
//TODO UROS loop is duplication here, but needed for initialVisibleLayers, nrChildLayers
for (var i=0; i<this.projectSettings.capability.layers.length; i++) {
var layer = this.projectSettings.capability.layers[i];
this.layerProperties[layer.name] = {
name: layer.name,
title: layer.title,
abstract: layer.abstract,
visible: layer.visible,
opacity: 255,
queryable: layer.queryable,
displayField: layer.displayField,
nrChildLayers: layer.nestedLayers.length,
attributes: layer.attributes,
srsList: layer.srs,
bbox: layer.llbbox,
minScale: (layer.minScale != null) ? parseFloat(layer.minScale) : null,
maxScale: (layer.maxScale != null) ? parseFloat(layer.maxScale) : null,
showLegend: layer.showLegend,
showMetadata: layer.showMetadata
};
this.layerTitleNameMapping[layer.title] = layer.name;
if (layer.visible) {
this.initialVisibleLayers.push(layer.name);
}
}
// defaults for GetCapabilities
if (this.projectSettings.capability.composerTemplates === undefined) {
this.projectSettings.capability.composerTemplates = [];
}
if (this.projectSettings.capability.exclusiveLayerGroups === undefined) {
this.projectSettings.capability.exclusiveLayerGroups = [];
}
//deal with callback function
if (typeof callback == "function") {
callback.apply(scope || node, [node]);
}
},
createWMSLayer: function(layer, url) {
if (layer.name) {
return new OpenLayers.Layer.WMS(
layer.title, url,
OpenLayers.Util.extend({
formats: layer.formats[0],
layers: layer.name
},
this.layerParams),
OpenLayers.Util.extend({
minScale: layer.minScale,
queryable: layer.queryable,
maxScale: layer.maxScale,
visible: layer.visible,
metadata: layer
}, this.layerOptions));
} else {
return null;
}
},
/**
* UROS: This function doesn't seem to work. There is no evaluate function
* @param layername
* @returns {undefined}
*/
findLayerNodeByName: function(layername) {
//goal of this function is to find a layer by its name
//we need to fork between IE 7/8 and modern browsers
var xpathExpr = '//opengis:Layer/opengis:Name[text()="'+layername+'"]/..';
var layerNode = undefined;
//case standard compliant browsers
if (typeof(this.WMSCapabilities.evaluate) == "function") {
xpathResult = this.WMSCapabilities.evaluate(xpathExpr,this.WMSCapabilities.firstChild,this.nsResolver,XPathResult.ANY_TYPE,null);
//type 4 = UNORDERED_NODE_ITERATOR_TYPE
if (xpathResult.resultType == 4) {
layerNode = xpathResult.iterateNext();
}
}
else {
//case older IEs
this.WMSCapabilities.setProperty("SelectionLanguage", "XPath");
this.WMSCapabilities.setProperty("SelectionNamespaces","xmlns:opengis='http://www.opengis.net/wms'");
layerNode = this.WMSCapabilities.selectSingleNode(xpathExpr);
}
return layerNode;
},
nsResolver: function(prefix) {
var ns = {
'opengis' : 'http://www.opengis.net/wms'
};
return ns[prefix] || null;
}
});
/**
* Remove dot from field name
* @param name
* @returns {string}
*/
function validateFieldName(name) {
var str='';
str=name.replace(/\./g,'');
return str;
}
/* ************************** QGIS.PrintProvider ************************** */
// extends GeoExt.data.PrintProvider
QGIS.PrintProvider = function(config) {
Ext.apply(this, config);
QGIS.PrintProvider.superclass.constructor.call(this,config);
};
Ext.extend(QGIS.PrintProvider, GeoExt.data.PrintProvider, {
print: function(map, pages, options) {
if (map instanceof GeoExt.MapPanel) {
map = map.map;
}
pages = pages instanceof Array ? pages : [pages];
options = options || {};
if(this.fireEvent("beforeprint", this, map, pages, options) === false) {
return;
}
//need to determine grid spacing
var mapScale = printExtent.page.scale.get("value");
var grid_interval = 10;
if (mapScale > 100 && mapScale <= 250) {
grid_interval = 25;
}
else if (mapScale > 250 && mapScale <= 1000) {
grid_interval = 50;
}
else if (mapScale > 1000 && mapScale <= 2500) {
grid_interval = 100;
}
else if (mapScale > 2500 && mapScale <= 5000) {
grid_interval = 250;
}
else if (mapScale > 5000 && mapScale <= 12000) {
grid_interval = 500;
}
else if (mapScale > 12000 && mapScale <= 25000) {
grid_interval = 1000;
}
else if (mapScale > 25000 && mapScale <= 50000) {
grid_interval = 2000;
}
else if (mapScale > 50000 && mapScale <= 100000) {
grid_interval = 5000;
}
else if (mapScale > 100000 && mapScale <= 500000) {
grid_interval = 10000;
}
else if (mapScale > 500000 && mapScale <= 1000000) {
grid_interval = 50000;
}
else if (mapScale > 1000000 && mapScale <= 5000000) {
grid_interval = 100000;
}
else if (mapScale > 5000000 && mapScale <= 10000000) {
grid_interval = 250000;
}
else if (mapScale > 10000000 && mapScale <= 50000000) {
grid_interval = 2500000;
}
else if (mapScale > 50000000 && mapScale <= 100000000) {
grid_interval = 5000000;
}
else if (mapScale > 100000000) {
grid_interval = 10000000;
}
// if the var fixedPrintResolution of GlobalOptions.js is set, the print resolution will be this value
if (fixedPrintResolution != null && parseInt(fixedPrintResolution) > 0){
printResolution = fixedPrintResolution;
} else {
printResolution = this.dpi.get("value");
}
var layers = [];
if(thematicLayer.params.LAYERS > '') {
layers = layers.concat(thematicLayer.params.LAYERS.split(','));
}
var extra = getVisibleExtraLayersForPrint();
var extraDefinition = '';
var baseDefinition = '';
if(extra.length>0) {
var extraNames = extra.map(function(item){return item.name;});
extraDefinition = extra.map(function(item){return item.definition;})[0]; //get only first one, ok?
layers.unshift(extraNames.join(','));
}
//add currently visible base layer for printing if exists in projects
if(currentlyVisibleBaseLayer) {
var printBaseLayer = wmsLoader.layerTitleNameMapping[currentlyVisibleBaseLayer];
if (printBaseLayer != undefined) {
layers.unshift(printBaseLayer);
} else {
var printBaseLayerOl2 = geoExtMap.map.getLayersByName(currentlyVisibleBaseLayer)[0];
var baseWms = getExternalWMSDefinition(printBaseLayerOl2);
if(baseWms) {
layers.unshift(baseWms.name);
baseDefinition = baseWms.definition;
}
}
}
if(this.additionalLayers.length>0) {
layers = layers.concat(this.additionalLayers);
}
//only check for reverse axis for QGIS 3.x, for QGIS 2 is false
var reverseAxisOrder = (Eqwc.settings.qgisVersion && parseInt(Eqwc.settings.qgisVersion)>2) ? OpenLayers.Projection.defaults[authid].yx : false;
var printUrl = this.url + '&' + Ext.urlEncode({
'SRS': authid,
'DPI': printResolution,
'TEMPLATE': this.layout.get("name"),
'map0:extent': printExtent.page.getPrintExtent(map).toBBOX(1, reverseAxisOrder),
'map0:scale': mapScale,
'map0:rotation': (printExtent.page.rotation * -1),
'map0:grid_interval_x': grid_interval,
'map0:grid_interval_y': grid_interval,
'LAYERS': layers.join(',')
});
printUrl += '&' + Ext.urlEncode(this.customParams);
if (thematicLayer.params.OPACITIES) {
printUrl += '&OPACITIES='+encodeURIComponent(thematicLayer.params.OPACITIES);
}
if (extraDefinition>'') {
printUrl += '&' + extraDefinition;
}
if (baseDefinition>'') {
printUrl += '&' + baseDefinition;
}
// add highlight
//var highlightParams = highlighter.printParams("map0");
//if (highlightParams != null) {
// printUrl += "&" + Ext.urlEncode(highlightParams);
//}
// makes spatial query from map to use the attributes in the print template (more in README chap 4.5)
// UROS DISABLED,found no reason for it. Looks like to read some values from layer print in qgis project
//var lonlat = printExtent.page.getPrintExtent(map).getCenterLonLat();
//var mapCenter = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
//var myfilter = new OpenLayers.Filter.Comparison({
// type: OpenLayers.Filter.Spatial.INTERSECTS,
// value: mapCenter
//});
//Ext.getBody().mask(printLoadingString[lang], 'x-mask-loading');
//var protocol = new OpenLayers.Protocol.WFS({
//
// url: printURI,
// featureType: 'print',
// geometryName: 'geometry',
// srsName: authid,
// filter: myfilter,
// readWithPOST: true
//});
this.fireEvent("afterprint", this, map, pages, options);
//protocol.read({
// callback: function(response) {
// try { // as some projects may have WFS disabled
// if(response.features != null) {
// if(response.features.length > 0) {
// attributes = response.features[0].attributes;
// for (key in attributes){
// printUrl += '&' + key + '=' + encodeURIComponent(attributes[key]);
// }
// }
// }
// } catch (e) {
// //console.log(e)
// }
this.download(printUrl);
// },
// scope: this
//});
},
download: function(url) {
if (this.fireEvent("beforedownload", this, url) !== false) {
//because of an IE bug one has to do it in two steps
var parentPanel = Ext.getCmp('geoExtMapPanel');
var pdfWindow = new Ext.Window(
{
title: printWindowTitleString[lang],
width: Ext.getBody().getWidth() - 100,
height: Ext.getBody().getHeight() - 100,
resizable: true,
closable: true,
constrain: true,
constrainHeader: true,
x:50,
y:50,
html: '<object data="'+url+'" type="application/pdf" width="100%" height="100%"><p style="margin:5px;">'+printingObjectDataAlternativeString1[lang] + url + printingObjectDataAlternativeString2[lang]
}
);
pdfWindow.show();
Ext.getBody().unmask();
}
this.fireEvent("print", this, url);
}
}
);
/* ************************** QGIS.SearchComboBox ************************** */
// extends Ext.form.ComboBox in order to display search results pulled in from a serverside python script
// sample taken from Swisstopo search combobox
QGIS.SearchComboBox = Ext.extend(Ext.form.ComboBox, {
map: null,
highlightLayerName: null,
highlightLayer: null,
hasReverseAxisOrder: false,
/** config
*/
url: null,
geomUrl: null,
// default Ext.form.ComboBox config
hideTrigger: false,
minChars: 2,
queryDelay: 50,
displayField: 'label',
forceSelection: true,
searchtables: null,
srs: null,
initComponent: function() {
//this.emptyText = searchFieldDefaultTextString[lang];
this.triggerConfig = { // we use a default clear trigger here
tag: "img", src: Ext.BLANK_IMAGE_URL, cls:'x-form-trigger x-form-clear-trigger'
};
this.on("keyUp", this.keyUpHandler);
this.on("afterrender", this.afterrenderHandler);
this.on("beforeselect", this.beforeselectHandler);
this.store = new Ext.data.JsonStore({
proxy: new Ext.data.ScriptTagProxy({
url: this.url,
method: 'GET',
callbackParam: 'cb',
nocache: false,
autoAbort: true
}),
baseParams: {
searchtables: this.getSearchTables(),
srs: this.srs
},
root: 'results',
fields: ['searchtable', 'searchtext', 'displaytext', 'bbox', 'showlayer', 'selectable']
});
this.tpl = new Ext.XTemplate(
'<tpl for="."><div class="x-combo-list-item {service}">',
'<tpl if="searchtable == null">',
'<b>',
'</tpl>',
'{displaytext}',
'<tpl if="searchtable == null">',
'</b>',
'</tpl>',
'</div></tpl>').compile();
QGIS.SearchComboBox.superclass.initComponent.call(this);
//reference to highlightLayer
if (this.highlightLayerName) {
this.highlightLayer = this.map.getLayersByName(this.highlightLayerName)[0];
}
this.on("select", this.recordSelected, this);
},
// private
afterrenderHandler: function() {
this.trigger["hide"]();
},
beforeselectHandler: function(combo,record,index) {
if (record.get('selectable') == "1") {
this.collapse();
}
},
keyUpHandler: function(cmp, e) {
//reset if user deleted last sign
this.checkTrigger();
if (Ext.isEmpty(this.getValue())) {
this.resetSearch();
}
//collapse if less than minChars are left
if (this.getValue().length < this.minChars) {
this.collapse();
}
},
checkTrigger: function() {
// show trigger only if there is any input
if (this.rendered) {
this.trigger[!Ext.isEmpty(this.getValue()) ? 'show': 'hide']();
}
},
onTriggerClick: function() {
// reimplements default onTriggerClick function (which does nothing)
this.resetSearch();
this.checkTrigger();
this.focus();
},
onSelect: function(record, index){
if(this.fireEvent('beforeselect', this, record, index) !== false){
if (record.get('selectable') == "1") {
this.setValue(record.get('displaytext'));
this.fireEvent('select', this, record, index);
}
}
},
resetSearch: function(){
this.collapse();
this.clearSearchResult();
},
/**
* Activated on selection of the search result item.
* An AJAX call retrieves the geometry from the server
* and highights it on the map.
*
* @param object combo
* @param object record
* @param int index
*/
recordSelected: function (combo, record, index) {
var bbox = record.get('bbox');
if (bbox != null) {
var extent = OpenLayers.Bounds.fromArray(bbox, this.hasReverseAxisOrder);
//make sure that map extent is not too small for point data
//need to improve this for units other than "m", e.g. degrees
var extWidth = extent.getWidth();
var extHeight = extent.getHeight();
if (extWidth < 50) {
centerX = extent.left + extWidth * 0.5;
extent.left = centerX - 25;
extent.right = centerX + 25;
}
else {
extent.left -= extWidth * 0.05;
extent.right += extWidth * 0.05;
}
if (extHeight < 50) {
centerY = extent.bottom + extHeight * 0.5;
extent.bottom = centerY - 25;
extent.top = centerY + 25;
}
else {
extent.bottom -= extHeight = 0.05;
extent.top += extHeight = 0.05;
}
//need to check if extent is too small
this.map.zoomToExtent(extent);
}
if (this.highlightLayer) {
//network request to get real wkt geometry of search object
Ext.Ajax.request({
url: this.geomUrl,
success: this.showSearchGeometry,
failure: function (result, request) {
Ext.MessageBox.alert(errMessageSearchComboNetworkRequestFailureTitleString[lang], errMessageSearchComboNetworkRequestFailureString + result.responseText);
},
method: 'GET',
params: {
searchtable: record.get('searchtable'),
showlayer: record.get('showlayer'),
displaytext: record.get('displaytext'),
srs: this.srs
}
});
}
},
// This event is called after a successfull retrieval of the geometry
// from the server. If the requested 'searchtable' is a valid layer
// name and if the autoActivateSearchGeometryLayer = true, then the layer
// is made visible.
// This should work out of the box if you are using PHP scripts.
showSearchGeometry: function(result, request) {
// Check if we need to activate the layer and the layers exists...
var showLayerName = request.params.showlayer ? request.params.showlayer: request.params.searchtable;
var layerId = wmsLoader.layerTitleNameMapping[showLayerName];
if( typeof autoActivateSearchGeometryLayer != 'undefined'
&& autoActivateSearchGeometryLayer
&& allLayers.indexOf(layerId) != -1 )
{
var found = false;
layerTree.root.cascade(function(n){
if(n.text==showLayerName){
found=n;
}
});
if(found){
// Bring it up!
found.getUI().toggleCheck(true);
// Spread the word ...
layerTree.fireEvent("leafschange");
}
}
this.highlightLayer.removeAllFeatures();
var feature = new OpenLayers.Feature.Vector(OpenLayers.Geometry.fromWKT(result.responseText));
this.highlightLayer.addFeatures([feature]);
},
clearSearchResult: function() {
this.setValue("");
if (this.highlightLayer) {
this.highlightLayer.removeAllFeatures();
}
},
getSearchTables: function() {
returnVal = null;
if (this.searchtables != null) {
returnVal = this.searchtables;
}
return returnVal;
}
});
/** api: xtype = qgis_searchcombo */
Ext.reg("qgis_searchcombo", QGIS.SearchComboBox);
/* *************************** QGIS.SearchPanel **************************** */
// extends Ext.Panel with a search form and a list of search results
QGIS.SearchPanel = Ext.extend(Ext.Panel, {
form: null,
featureInfoParser: null,
store: null,
resultsGrid: null,
// config
/**
* Search request method:
* false: submit search form using URL rewriting
* true: submit WMS GetFeatureInfo request
*/
useWmsRequest: false,
/**
* WMS layer name for GetFeatureInfo request
* required if useWmsRequest is true
*/
/**
* Attribute filter that is added to request
*/
wmsFilter: '',
useBbox: false,
queryLayer: '',
/**
* single item or array of child components to be added as form fields (see Ext.form.FormPanel.items)
*/
formItems: [],
/**
* array of columns for results grid (see Ext.grid.GridPanel.columns)
*/
gridColumns: [],
/**
* WMS layer name for feature selection
*/
selectionLayer: '',
/**
* zoom level for feature selection
*/
selectionZoom: 4,
/**
* position of result grid (empty=default=left side, for other values look mapSearchPanelOutputRegion
*/
gridLocation: '',
gridTitle: '',
gridResults: 100,
gridResultsPageSize: 20,
gridEditable: false,
tabClosable: true,
constructor: function (config) {
config = config || {};
config.useWmsRequest = config.useWmsRequest || false;
config.useBbox = config.useBbox || false;
if(config.tabClosable == null) {
config.tabClosable = true;
}
if(config.gridEditable == null) {
config.gridEditable = false;
}
config.queryLayer = config.queryLayer || '';
config.wmsFilter = config.wmsFilter || '';
config.formItems = config.formItems || [];
config.gridColumns = config.gridColumns || [];
config.gridLocation = config.gridLocation || '';
config.gridTitle = config.gridTitle || '';
if (config.gridResults == null) {
config.gridResults = 100;
}
if (config.gridResultsPageSize == null) {
config.gridResultsPageSize = 20;
}
config.selectionLayer = config.selectionLayer || '';
if (config.selectionZoom == null) {
config.selectionZoom = 4;
}
this.addEvents(['beforesearchdataloaded', 'aftersearchdataloaded', 'searchformsubmitted']);
QGIS.SearchPanel.superclass.constructor.call(this, config);
},
initComponent: function() {
this.form = new Ext.form.FormPanel({
autoHeight: true,
bodyBorder: false,
padding: 3,
defaults: {
anchor: '-10'
},
items: this.formItems,
buttons: [
{
text: searchButtonString[lang],
scope: this,
handler: this.onSubmit
},
{
text: resetButtonString[lang],
scope: this,
handler: function() {
this.fireEvent("featureselectioncleared");
this.form.getForm().reset();
}
}
],
keys: [
{
key: [Ext.EventObject.ENTER],
handler: function() {
this.onSubmit();
},
scope: this
}
]
});
this.featureInfoParser = new QGIS.FeatureInfoParser();
Ext.apply(this, {
layout: 'fit',
autoHeight: true,
items: [
this.form
]
});
QGIS.SearchPanel.superclass.initComponent.call(this);
this.addEvents("featureselected");
this.addEvents("featureselectioncleared");
//Ext.Ajax.on('requestexception', this.onAjaxRequestException, this);
},
onSubmit: function(reload) {
if(this.form !== null) {
if(this.form.getForm().isValid()===false){
return;
}
}
//test
//if (this.store !== null) {
// this.store.removeAll();
//}
// Moved to try/catch because of wierd error in popup implementation
// when submitting from different search panel.
//try {
// this.resultsGrid.hide();
//} catch (e) {
// // Logging?
//}
this.fireEvent("featureselectioncleared");
this.fireEvent("searchformsubmitted");
//loading mask
var maskElement = this;
if(this.gridLocation=='bottom') {
maskElement = Ext.getCmp('BottomPanel');
}
//moved
// Make sure it's shown and expanded
//maskElement.show();
//maskElement.collapsible && maskElement.expand();
if (this.useWmsRequest) {
//alert(maskElement.id);
//check if we already have table for layer in case of open table call
if (this.resultsGrid !== null && this.resultsGrid.store !== null) {
if (maskElement.id=='BottomPanel' && this.gridResults === this.resultsGrid.store.maxResults && !this.useBbox && !reload) {
maskElement.activate(Ext.getCmp('table_' + this.queryLayer));
}
else {
this.resultsGrid.store.maxResults = this.gridResults;
this.submitGetFeatureInfo();
}
}
else {
maskElement.el.mask(pleaseWaitString[lang], 'x-mask-loading');
this.submitGetFeatureInfo();
}
} else {
this.submitForm();
}
},
submitGetFeatureInfo: function() {
var storedFilter = this.wmsFilter;
var layerId = wmsLoader.layerTitleNameMapping[this.queryLayer];
var fieldsValidate = true;
if (storedFilter == "") {
var filter = [];
var fieldValues = this.form.getForm().getFieldValues();
for (var key in fieldValues) {
var field = this.form.getForm().findField(key);
// Only add if not blank
if (fieldValues[key]) {
var filterOp = field.initialConfig.filterOp ? field.initialConfig.filterOp : "=";
if (field.isXType('numberfield')) {
valueQuotes = "";
}
else {