-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
hcmgis_dialogs.py
2766 lines (2453 loc) · 155 KB
/
hcmgis_dialogs.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# hcmgisgis_dialogs - Dialog classes for hcmgis
#
# begin : 01/02/2018
# copyright : (c) 2018 by Quach Dong Thang
# email : quachdongthang@gmail.com
# --------------------------------------------------------
"""
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License v3.0. *
* *
***************************************************************************/
"""
import csv
import math
import os.path
import operator
import sys
from urllib.request import urlopen
import json
from qgis.core import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from owslib.wfs import WebFeatureService
#from owslib.ogcapi import Features
from qgis.gui import QgsMessageBar
import qgis.utils
from glob import glob
import urllib, re, ssl
from time import sleep
from xml.etree.ElementTree import XML, fromstring
import webbrowser
from PyQt5.QtWidgets import QApplication
try:
from .hcmgis_library import *
except:
from hcmgis_library import *
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/forms")
from hcmgis_opendata_form import *
from hcmgis_geofabrik_form import *
from hcmgis_gadm_form import *
from hcmgis_wof_form import *
from hcmgis_microsoft_form import *
from hcmgis_global_microsoft_form import *
from hcmgis_font_convert_form import *
from hcmgis_split_field_form import *
from hcmgis_merge_field_form import *
from hcmgis_medialaxis_form import *
from hcmgis_centerline_form import *
from hcmgis_closestpair_form import *
from hcmgis_lec_form import *
from hcmgis_customprojections_form import *
from hcmgis_format_convert_form import *
from hcmgis_csv2shp_form import *
from hcmgis_txt2csv_form import *
from hcmgis_xls2csv_form import *
from hcmgis_mapbox_form import *
from hcmgis_split_polygon_form import *
# ------------------------------------------------------------------------------
# hcmgis_dialog - base class for hcmgis dialogs containing utility functions
# ------------------------------------------------------------------------------
class hcmgis_dialog(QtWidgets.QDialog):
def __init__(self, iface):
QtWidgets.QDialog.__init__(self)
self.iface = iface
def hcmgis_initialize_spatial_output_file_widget(self, file_widget, name, ext = ".shp"):
initial_file_name = self.hcmgis_temp_file_name(name, ext)
file_widget.setFilePath(initial_file_name)
file_widget.setStorageMode(QgsFileWidget.SaveFile)
file_widget.setFilter("ESRI Shapefile (*.shp);;GeoJSON (*.geojson);;KML (*.kml);;" + \
"Spatialite (*.sqlite);;GPKG (*.gpkg)")
def hcmgis_temp_file_name(self, name, ext):
project = QgsProject.instance()
home_path = project.homePath()
if not home_path:
home_path = os.path.expanduser('~')
for x in range(1, 10):
file_name = home_path + "/" +name + str(x) + ext
if not os.path.isfile(file_name):
return file_name
return home_path + "/"+ name + ext
def hcmgis_read_csv_header(self, input_csv_name):
# This may take awhile with large CSV files
input_csv = QgsVectorLayer(input_csv_name)
field_names = []
if (not input_csv) or (input_csv.featureCount() <= 0) or (len(input_csv.fields()) <= 0):
return field_names
for field in input_csv.fields():
field_names.append(field.name())
return field_names
def hcmgis_direct_read_csv_header(self, filename):
try:
infile = open(filename, 'r', encoding='utf-8')
except Exception as e:
return "Failure opening " + filename + ": " + str(e)
try:
dialect = csv.Sniffer().sniff(infile.read(8192))
except Exception as e:
return "Bad CSV file " + filename + ": " + str(e) + "(verify that your delimiters are consistent)"
infile.seek(0)
reader = csv.reader(infile, dialect)
header = next(reader)
del reader
infile.close()
del infile
if len(header) <= 0:
return filename + " does not appear to be a CSV file"
return header
def hcmgis_fill_list_widget_with_vector_layers(self, list_widget):
# Add layers not in the list
for layer in self.iface.mapCanvas().layers():
if layer.type() == QgsMapLayer.VectorLayer:
found = False
for index in range(list_widget.count()):
if list_widget.item(index).text() == layer.name():
found = True
break
if not found:
list_widget.addItem(layer.name())
# Remove layers no longer on the map
removed = []
for index in range(list_widget.count()):
found = False
for layer in self.iface.mapCanvas().layers():
if layer.name() == list_widget.item(index).text():
found = True
break
if not found:
removed.append(index)
removed.reverse()
for index in removed:
item = list_widget.takeItem(index)
item = None
# list_widget.removeItemWidget(list_widget.item(index))
def hcmgis_set_status_bar(self, status_bar, status_lable):
status_bar.setMinimum(0)
status_bar.setMaximum(100)
status_bar.setValue(0)
status_bar.setFormat("Ready")
self.status_bar = status_bar
self.status_lable = status_lable
def hcmgis_status_callback(self, percent_complete, lable):
try:
self.status_lable.setText(lable)
message = str(int(percent_complete)) + "%"
self.status_bar.setFormat(message)
if percent_complete < 0:
self.status_bar.setValue(0)
elif percent_complete > 100:
self.status_bar.setValue(100)
else:
self.status_bar.setValue(percent_complete)
self.iface.statusBarIface().showMessage(message)
# print("status_callback(" + message + ")")
except:
print(message)
# add handling of "Close" button
return 0
server_types = ['WFS',
'OGC API - Features'
]
arcgis_servers = []
arcgis_urls = []
wfs_servers = [
# 'HCMGIS OpenData',
'BecaGIS OpenData',
# 'OpenDevelopment Mekong',
# 'OpenDevelopment Cambodia',
# 'OpenDevelopment Laos',
# 'OpenDevelopment Myanmar',
# 'OpenDevelopment Vietnam',
'ISTI-CNR Pisa',
'Stanford University',
# 'CAEARTE-CONAE',
'IBGE',
'INDE',
# 'ISRIC Data Hub',
# 'World Food Programme',
# 'PUMA - World Bank Group' ,
]
wfs_urls = [
# 'https://opendata.hcmgis.vn/geoserver',
'https://opendata.becagis.vn/geoserver',
# 'https://data.opendevelopmentmekong.net/geoserver/ODMekong',
# 'https://data.opendevelopmentmekong.net/geoserver/ODCambodia',
# 'https://data.opendevelopmentmekong.net/geoserver/ODLao',
# 'https://data.opendevelopmentmekong.net/geoserver/ODMyanmar',
# 'https://data.opendevelopmentmekong.net/geoserver/ODVietnam',
'http://geoserver.d4science.org:80/geoserver',
'https://geowebservices.stanford.edu:443/geoserver',
# 'http://ambiente.caearte.conae.gov.ar/geoserver',
# 'http://openapi.aurin.org.au/public',
'https://geoservicos.ibge.gov.br/geoserver',
'https://geoservicos.inde.gov.br/geoserver',
# 'https://data.isric.org/geoserver',
# 'https://geonode.wfp.org/geoserver',
# 'https://puma.worldbank.org/geoserver'
]
ogc_servers = [
# 'Local GeoServer',
# 'Local PyGeoAPI',
'GeoSolutions (GeoServer)',
'Sammeldienst Kreis Viersen (QGIS Server)',
'OSM-Daten Kreis Viersen (QGIS Server)',
'MS4W Demo OGCAPI Server (UMN MapServer)',
'NRW Topographie (Ldproxy)',
# 'Montreal Building (Ldproxy)',
'CShapes Dataset of Historical Country Boundaries (Ldproxy)',
'Daraa - Syria (Ldproxy)',
'OS Open Zoomstack (Ldproxy)',
'Straßennetz Landesbetrieb Straßenbau NRW'
'Geoconnex (Pygeoapi)',
'US Geoplatform (Pygeoapi)',
'Meteorological Services of Canada (Pygeoapi)',
'Pygeoapi Demo'
]
ogc_urls = [
# 'http://localhost:8080/geoserver/ogc/features',
# 'http://localhost:5000',
# 'https://gs-main.geosolutionsgroup.com/geoserver/ogc/features',
'https://geo.kreis-viersen.de/ows/sammeldienst/wfs3',
'https://geo.kreis-viersen.de/ows/osm-daten/wfs3',
'https://demo.mapserver.org/cgi-bin/mapserv/localdemo/ogcapi',
'https://www.ldproxy.nrw.de/topographie',
# 'https://d123.ldproxy.net/montreal',
'https://demo.ldproxy.net/cshapes',
'https://demo.ldproxy.net/daraa',
'https://demo.ldproxy.net/zoomstack',
'https://demo.ldproxy.net/strassen',
'https://reference.geoconnex.us',
'https://geoapi.geoplatform.gov',
'https://api.weather.gc.ca',
'https://demo.pygeoapi.io/master '
]
wfs_formats = [
'SHAPE-ZIP',
'JSON',
'KML',
'CSV',
'GML',
'XLSX'
]
ogc_formats = [
'JSON',
'JSONLD',
'KML',
'CSV',
'GML'
]
def hcmgis_fill_table_widget_with_csv(self,table_widget, csv_file, status_callback = None):
data = []
with open(csv_file, 'r') as stream:
for rowdata in csv.reader(stream):
data.append(rowdata)
labels = data[0]
del data[0]
nb_row = len(data)
nb_col = len(data[0])
table_widget.setRowCount(nb_row)
table_widget.setColumnCount(nb_col)
table_widget.setHorizontalHeaderLabels(labels)
for row in range (nb_row):
for col in range(nb_col):
item = QTableWidgetItem(str(data[row][col]))
table_widget.setItem(row, col, item)
return
def hcmgis_fill_table_widget_with_json(self,table_widget, url, TxtTitle, TxtAbstract, status_callback = None):
table_widget.setRowCount(0)
TxtTitle.clear()
TxtAbstract.clear()
self.Filter.clear()
self.LblWFSLayers.clear()
# url_landingpage = self.ogc_urls[idx]
url_landingpage = url
# url_landingpage = url + '/?f=json'
url_collections = url +'/collections/?f=json'
try:
try:
landingpage_response = urlopen(url_landingpage)
if (landingpage_response is not None):
server_json = json.loads(landingpage_response.read())
server_title = server_json['title']
server_abstract = server_json['description']
TxtTitle.insertPlainText(server_title)
TxtAbstract.insertPlainText(server_abstract)
except: pass
collections_response = urlopen(url_collections)
if collections_response is not None:
# storing the JSON response from url in data
data_json = json.loads(collections_response.read())
collections = data_json['collections']
if len(collections) > 0:
i = 0
for i in range (len(collections)):
table_widget.insertRow(i)
try:
table_widget.setItem(i,0, QTableWidgetItem(collections[i]['id']))
except:
table_widget.setItem(i,0, QTableWidgetItem(collections[i]['name']))
table_widget.setItem(i,1, QTableWidgetItem(collections[i]['title']))
table_widget.item(i,0).setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
table_widget.item(i,1).setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
status_callback(((i+1)/len(collections))*100,None)
message = str(i+1) + " layers loaded"
MessageBar = qgis.utils.iface.messageBar()
MessageBar.pushMessage(message, 0, 2)
self.LblWFSLayers.setText(message)
self.Filter.setEnabled(True)
self.Filter.setFocus(True)
else:
message = " 0 layer loaded"
self.LblWFSLayers.setText(message)
MessageBar = qgis.utils.iface.messageBar()
MessageBar.pushMessage(message, 0, 2)
self.Filter.setEnabled(False)
self.Filter.setFocus(False)
else: return
except Exception as e:
QMessageBox.warning(None, "Connection Error",str(e))
return
return
def hcmgis_fill_table_widget_with_wfs_layers0(self,table_widget, url, TxtTitle, TxtAbstract, status_callback = None):
table_widget.setRowCount(0)
TxtTitle.clear()
TxtAbstract.clear()
self.Filter.clear()
self.LblWFSLayers.clear()
idx = self.cboServerName.currentIndex()
# try:
ssl._create_default_https_context = ssl._create_unverified_context
#wfs = urllib.request.urlopen(self.wfs_urls[idx] +'/ows?service=wfs&version=2.0.0&request=GetCapabilities',context=ssl._create_unverified_context())
#wfs = urllib.request.urlopen(self.wfs_urls[idx] +'/ows?service=wfs&version=2.0.0&request=GetCapabilities')
#wfs = requests.get(self.wfs_urls[idx] +'/ows?service=wfs&version=2.0.0&request=GetCapabilities',verify = False)
# uri = self.wfs_urls[idx] +'/wfs?version=2.0.0&request=GetCapabilities'
# uri = self.wfs_urls[idx] +'/wfs?request=GetCapabilities'
uri = url +'/wfs?request=GetCapabilities'
wfs = requests.get(uri, stream=True, allow_redirects=True, verify = False)
# try:
# uri = url +'/wfs?request=GetCapabilities' #for GeoServer
# print (uri)
# wfs = requests.get(uri, stream=True, allow_redirects=True, verify = False)
# print (wfs.text)
# except:
# uri = url +'?service=WFS&request=GetCapabilities' #for UMN MapServer
# print (uri)
# wfs = requests.get(uri, stream=True, allow_redirects=True, verify = False)
# print (wfs.text)
project = QgsProject.instance()
home_path = project.homePath()
if not home_path:
home_path = os.path.expanduser('~')
filename = home_path + "/"+ str(self.wfs_servers[idx]) + ".xml"
# print (filename)
if (wfs.status_code == 200):
f = open(filename, 'wb')
for chunk in wfs.iter_content(chunk_size = 1024):
if not chunk:
break
f.write(chunk)
f.close()
try:
if wfs is not None:
#data = wfs.read().decode('utf-8')
#data = wfs.text
getcapabilities = open(filename, 'r')
data = getcapabilities.read()
getcapabilities.close()
os.remove(filename)
# print (data)
server_title_regex = r'<ows:Title>(.+?)</ows:Title>|<ows:Title/>'
#server_title_pattern = re.compile(server_title_regex)
server_abstract_regex = r'<ows:Abstract>(.+?)</ows:Abstract>|<ows:Abstract/>'
#server_abstract_pattern = re.compile(server_abstract_regex)
server_title = re.findall(server_title_regex,data,re.DOTALL)
server_abstract = re.findall(server_abstract_regex,data,re.DOTALL)
layer_name_regex = r'<Name>(.+?)</Name>'
#layer_name_pattern = re.compile(layer_name_regex)
layer_title_regex = r'<Title>(.+?)</Title>|<Title/>'
#layer_title_pattern = re.compile(layer_title_regex)
layer_name = re.findall(layer_name_regex,data,re.DOTALL)
layer_title = re.findall(layer_title_regex,data,re.DOTALL)
if len(server_title)>0:
TxtTitle.insertPlainText(server_title[0])
if len (server_abstract)>0:
TxtAbstract.insertPlainText(server_abstract[0].replace(' ','')) #delete unwanted character before \n
# QMessageBox.information(None, "Congrats",str(layer_name))
if len(layer_name)>0:
# print (layer_name)
i = 0
for i in range (len(layer_name)):
# # Feature count
# r = requests.get(self.wfs_urls[idx]+'/wfs', params={
# 'service': 'WFS',
# 'version': '1.1',
# 'request': 'GetFeature',
# 'resultType': 'hits',
# 'typename': layer_name[i]
# })
# myxml = fromstring(r.content)
# feature_count = myxml.attrib['numberOfFeatures']
table_widget.insertRow(i)
table_widget.setItem(i,0, QTableWidgetItem(layer_name[i]))
table_widget.setItem(i,1, QTableWidgetItem(layer_title[i]))
# table_widget.setItem(i,2, QTableWidgetItem(feature_count))
table_widget.item(i,0).setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
table_widget.item(i,1).setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
# status_callback((i/len(layer_name))*100,None)
status_callback(((i+1)/len(layer_name))*100,None)
message = str(i+1) + " WFS layers loaded"
self.LblWFSLayers.setText(message)
MessageBar = qgis.utils.iface.messageBar()
MessageBar.pushMessage(message, 0, 2)
self.Filter.setEnabled(True)
self.Filter.setFocus(True)
else:
message = " 0 WFS layer loaded"
self.LblWFSLayers.setText(message)
MessageBar = qgis.utils.iface.messageBar()
MessageBar.pushMessage(message, 0, 2)
self.Filter.setEnabled(False)
self.Filter.setFocus(False)
else: return
except Exception as e:
QMessageBox.warning(None, "WFS Error",str(e))
return
def hcmgis_fill_table_widget_with_wfs_layers(self,table_widget, idx, TxtTitle, TxtAbstract, status_callback = None):
table_widget.clear()
table_widget.setRowCount(0)
TxtTitle.clear()
TxtAbstract.clear()
columns = ['Name', 'Title']
table_widget.setColumnCount(len(columns))
table_widget.setHorizontalHeaderLabels(columns)
try:
wfs = WebFeatureService(self.wfs_urls[idx] +'/wfs', version = '2.0.0')
if wfs is not None:
TxtTitle.insertPlainText(wfs.identification.title)
TxtAbstract.insertPlainText(wfs.identification.abstract)
layer_names = list(wfs.contents)
if layer_names is not None:
i = 0
for layer_name in layer_names:
table_widget.insertRow(i)
table_widget.setItem(i,0, QTableWidgetItem(layer_name))
table_widget.setItem(i,1, QTableWidgetItem(wfs[layer_name].title))
table_widget.item(i,0).setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
table_widget.item(i,1).setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
i+=1
status_callback((i/len(layer_names))*100,None)
message = str(i) + " WFS layers loaded"
MessageBar = qgis.utils.iface.messageBar()
MessageBar.pushMessage(message, 0, 2)
else: return
else: return
except Exception as e:
QMessageBox.warning(None, "WFS ERROR",str(e))
return
# --------------------------------------------------------
# HCMGIS Opendata
# --------------------------------------------------------
class hcmgis_opendata_dialog(hcmgis_dialog, Ui_hcmgis_opendata_form):
def __init__(self, iface):
hcmgis_dialog.__init__(self, iface)
self.setupUi(self)
self.BtnApplyClose.button(QtWidgets.QDialogButtonBox.Close).setAutoDefault(False)
self.Filter.setFocus(True)
QWidget.setTabOrder(self.Filter, self.TblWFSLayers)
self.BtnOutputFolder.clicked.connect(self.browse_outfile)
project = QgsProject.instance()
home_path = project.homePath()
if not home_path:
home_path = os.path.expanduser('~')
self.LinOutputFolder.setText(home_path)
self.ChkSaveShapefile.stateChanged.connect(self.toggleouputfolder)
columns = ['Name', 'Title']
self.TblWFSLayers.setColumnCount(len(columns))
self.TblWFSLayers.setHorizontalHeaderLabels(columns)
self.TblWFSLayers.resizeColumnsToContents()
self.TblWFSLayers.resizeRowsToContents()
self.TblWFSLayers.horizontalHeader().setStretchLastSection(True)
self.Filter.setEnabled(False)
self.Filter.valueChanged.connect(self.updateWFSTable)
# self.TblWFSLayers.setDragDropMode(QAbstractItemView.DragOnly)
# self.TblWFSLayers.setDragEnabled(True)
self.cboServerType.addItems(self.server_types)
self.cboServerType.setCurrentIndex(-1)
self.cboServerType.currentIndexChanged.connect(self.updateServer)
self.cboServerName.currentIndexChanged.connect(self.updateURL)
self.cboServerName.setCurrentIndex(-1)
# self.cboServerName.currentIndexChanged.connect(self.readwfs)
self.cboFormat.setEnabled(False)
self.hcmgis_set_status_bar(self.status,self.LblStatus)
self.cboServerName.setStyleSheet("QComboBox {combobox-popup: 0; }") # To enable the setMaxVisibleItems
self.cboServerName.setMaxVisibleItems(10)
self.cboServerName.view().setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.TblWFSLayers.doubleClicked.connect(self.run)
self.BtnApplyClose.button(QtWidgets.QDialogButtonBox.Apply).clicked.connect(self.run)
# self.BtnApplyClose.button(QtWidgets.QDialogButtonBox.Close).clicked.connect(self.closeDialog)
# def closeDialog(self):
# QApplication.setOverrideCursor(Qt.ArrowCursor)
# self.close()
def updateWFSTable(self):
name = self.Filter.text().lower()
if (name != '' and name is not None):
visible_row = 0
for row in range(self.TblWFSLayers.rowCount()):
item0 = self.TblWFSLayers.item(row, 0) # Layer Name
item1 = self.TblWFSLayers.item(row, 1) # Layer Title
# if the search is *not* in the item's text *do not hide* the row
if (name not in item0.text().lower() and name not in item1.text().lower()):
match = True
else:
match = False
visible_row += 1
self.TblWFSLayers.setRowHidden(row, match )
if visible_row < self.TblWFSLayers.rowCount():
self.LblWFSLayers.setText(str(visible_row) + ' Layers filterd')
else:
for row in range(self.TblWFSLayers.rowCount()):
self.TblWFSLayers.setRowHidden(row, False )
self.LblWFSLayers.setText(str(self.TblWFSLayers.rowCount()) + ' Layers loaded')
def updateServer(self):
self.cboServerName.clear()
self.TxtTitle.clear()
self.TxtAbstract.clear()
self.TblWFSLayers.setRowCount(0)
# if self.cboServerType.currentIndex() == 0: #'WFS'
# self.cboServerName.addItems(self.wfs_servers)
# elif self.cboServerType.currentIndex() == 1: #'OGC APIs'
# self.cboServerName.addItems(self.ogc_servers)
if self.cboServerType.currentIndex() == 0: #'WFS'
self.cboServerName.addItems(self.wfs_servers)
# self.cboServerName.currentIndexChanged.connect(self.readwfs)
self.BtnConnect.clicked.connect(self.readwfs)
self.cboFormat.clear()
self.cboFormat.addItems(self.wfs_formats)
elif self.cboServerType.currentIndex() == 1: #'OGC APIs'
self.cboServerName.addItems(self.ogc_servers)
self.BtnConnect.clicked.connect(self.readwfs)
self.cboFormat.clear()
self.cboFormat.addItems(self.ogc_formats)
def updateURL(self):
self.TblWFSLayers.setRowCount(0)
self.TxtTitle.clear()
self.TxtAbstract.clear()
self.Filter.clear()
self.TxtURL.clear()
self.LblStatus.clear()
self.LblWFSLayers.clear()
idx = self.cboServerName.currentIndex()
if (self.cboServerType.currentIndex() == 0 and self.cboServerName.currentIndex()>-1):
self.TxtURL.setText(self.wfs_urls[idx])
elif (self.cboServerType.currentIndex() == 1 and self.cboServerName.currentIndex()>-1):
self.TxtURL.setText(self.ogc_urls[idx])
def readwfs(self):
self.TxtTitle.clear()
self.TxtAbstract.clear()
self.TblWFSLayers.setRowCount(0)
self.LblStatus.clear()
self.hcmgis_set_status_bar(self.status,self.LblStatus)
self.BtnConnect.setEnabled(False)
# idx = self.cboServerName.currentIndex()
# QApplication.setOverrideCursor(Qt.WaitCursor)
# do lengthy process
url = self.TxtURL.text().strip()
if (self.cboServerType.currentIndex() == 0 and self.cboServerName.currentIndex()>-1):
self.LblWFSLayers.setText('WFS Layers')
#self.hcmgis_fill_table_widget_with_wfs_layers(self.TblWFSLayers,self.cboServerName.currentIndex(), self.TxtTitle,self.TxtAbstract,self.hcmgis_status_callback)
self.hcmgis_fill_table_widget_with_wfs_layers0(self.TblWFSLayers,url, self.TxtTitle,self.TxtAbstract,self.hcmgis_status_callback)
elif (self.cboServerType.currentIndex() == 1 and self.cboServerName.currentIndex()>-1):
self.LblWFSLayers.setText('OGC API Layers')
#self.hcmgis_fill_table_widget_with_wfs_layers(self.TblWFSLayers,self.cboServerName.currentIndex(), self.TxtTitle,self.TxtAbstract,self.hcmgis_status_callback)
self.hcmgis_fill_table_widget_with_json(self.TblWFSLayers,url, self.TxtTitle,self.TxtAbstract,self.hcmgis_status_callback)
self.BtnConnect.setEnabled(True)
# QApplication.setOverrideCursor(Qt.ArrowCursor)
def togglesave(self):
self.ChkSaveShapefile.setChecked(self.cboFormat.currentIndex()>0)
def browse_outfile(self):
newname = QFileDialog.getExistingDirectory(None, "Output Folder",self.LinOutputFolder.displayText())
if newname != None:
self.LinOutputFolder.setText(newname)
def toggleouputfolder(self,state):
if state > 0:
self.LinOutputFolder.setEnabled(True)
self.BtnOutputFolder.setEnabled(True)
self.cboFormat.setEnabled(True)
else:
self.LinOutputFolder.setEnabled(False)
self.BtnOutputFolder.setEnabled(False)
self.cboFormat.setEnabled(False)
def run(self):
if self.cboServerType.currentIndex() == 0: #WFS
self.loadwfs()
elif self.cboServerType.currentIndex() == 1: #OGC API
self.loadogc()
def loadwfs(self):
self.hcmgis_set_status_bar(self.status,self.LblStatus)
self.LblStatus.clear()
idx = self.cboServerName.currentIndex()
# opendata_url =self.wfs_urls[idx]
opendata_url =self.TxtURL.text().strip()
outdir = unicode(self.LinOutputFolder.displayText())
wfs_format = self.cboFormat.currentText().lower()
unzip_folder = ''
ext = "." + wfs_format
if (wfs_format == "shape-zip"):
ext = ".zip"
elif (wfs_format == "xlsx"):
wfs_format = "excel2007"
elif (wfs_format == "gml"):
wfs_format = "gml3"
layernames = []
rows = []
for index in self.TblWFSLayers.selectedIndexes():
if index.row() not in rows:
rows.append(index.row())
for row_index in rows:
if (self.TblWFSLayers.item(row_index, 0) is not None):
layernames.append(self.TblWFSLayers.item(row_index, 0).text())
# print(rows)
if layernames is not None:
ii = 0
for layer_name in layernames:
# uri = opendata_url + "/wfs?version=1.0.0&request=GetFeature&format_options=CHARSET:UTF-8&typename="+ str(layer_name)
uri = opendata_url + "/wfs?request=GetFeature&format_options=CHARSET:UTF-8&typename="+ str(layer_name)
#uri = opendata_url + "/ows?service=WFS&request=GetFeature&typename="+ str(layer_name)
if (not self.ChkSaveShapefile.isChecked()):
try:
qgis.utils.iface.addVectorLayer(uri, layer_name,"WFS")
qgis.utils.iface.zoomToActiveLayer()
ii+=1
self.LblStatus.setText (str(ii)+"/ "+ str(len(layernames)) + " layers added")
percent_complete = ii/len(layernames)*100
self.status.setValue(percent_complete)
message = str(int(percent_complete)) + "%"
self.status.setFormat(message)
except Exception as e:
QMessageBox.critical(self.iface.mainWindow(), "WFS", e)
else:
#uri = opendata_url + "/ows?service=WFS&request=GetFeature&typename="+ str(layer_name)
uri += '&outputFormat='
uri += wfs_format
try:
if wfs_format == "shape-zip":
headers = ""
contents = requests.get(uri, headers=headers, stream=True, allow_redirects=True, verify = False)
filename = outdir + "/"+ str(layer_name).replace(":","_") + ext
# total_size = int(len(contents.content))
# total_size_MB = round(total_size*10**(-6),2)
# chunk_size = int(total_size/100)
if (contents.status_code == 200):
f = open(filename, 'wb')
for chunk in contents.iter_content(chunk_size = 1024):
if not chunk:
break
f.write(chunk)
f.close()
unzip_folder = filename.replace('.zip','')
if not os.path.exists (unzip_folder):
os.mkdir(unzip_folder)
with zipfile.ZipFile(filename) as zip_ref:
zip_ref.extractall(unzip_folder)
wholelist = os.listdir(unzip_folder)
i = 0
for file in wholelist:
if ".cst" in file:
new_file_name = os.path.splitext(file)[0]+'.cpg'
if not os.path.exists (os.path.join(unzip_folder,new_file_name)):
os.rename(os.path.join(unzip_folder,file),os.path.join(unzip_folder,new_file_name))
if ".shp" in file:
fileroute= unzip_folder+'/'+file
layer = QgsVectorLayer(fileroute,file[:-4],"ogr")
if (layer.isValid()):
QgsProject.instance().addMapLayer(layer)
qgis.utils.iface.zoomToActiveLayer()
ii+=1
self.LblStatus.setText (str(ii)+"/ "+ str(len(layernames)) + " layers saved and added")
percent_complete = ii/len(layernames)*100
self.status.setValue(percent_complete)
message = str(int(percent_complete)) + "%"
self.status.setFormat(message)
else:
filename = outdir + "/"+ str(layer_name).replace(":","_") + ext
ssl._create_default_https_context = ssl._create_unverified_context
#urllib.request.urlretrieve(uri,filename,context=ssl._create_unverified_context())
# print (uri)
urllib.request.urlretrieve(uri,filename)
layer = QgsVectorLayer(filename, QFileInfo(filename).baseName(), 'ogr')
layer.dataProvider().setEncoding(u'UTF-8')
if (layer.isValid()):
QgsProject.instance().addMapLayer(layer)
qgis.utils.iface.zoomToActiveLayer()
ii+=1
self.LblStatus.setText (str(ii)+"/ "+ str(len(layernames)) + " layers saved and added")
percent_complete = ii/len(layernames)*100
self.status.setValue(percent_complete)
message = str(int(percent_complete)) + "%"
self.status.setFormat(message)
except Exception as e:
# qgis.utils.iface.addVectorLayer(uri, str(layer_name),"WFS")
QMessageBox.critical(self.iface.mainWindow(), "WFS", str(e))
return
def loadogc(self):
self.hcmgis_set_status_bar(self.status,self.LblStatus)
self.LblStatus.clear()
idx = self.cboServerName.currentIndex()
# opendata_url =self.ogc_urls[idx]
opendata_url =self.TxtURL.text().strip()
outdir = unicode(self.LinOutputFolder.displayText())
ogc_format = self.cboFormat.currentText().lower()
ext = "." + ogc_format
# if (ogc_format == "json"):
# ogc_format = "application/json"
if (ogc_format == "kml"):
ogc_format = "application%2Fvnd.google-earth.kml%2Bxml"
elif (ogc_format == "csv"):
ogc_format = "text%2Fcsv"
elif (ogc_format == "gml"):
ogc_format = "application%2Fgml%2Bxml%3Bversion%3D3.2"
layernames = []
rows = []
for index in self.TblWFSLayers.selectedIndexes():
if index.row() not in rows:
rows.append(index.row())
for row_index in rows:
if (self.TblWFSLayers.item(row_index, 0) is not None):
layernames.append(self.TblWFSLayers.item(row_index, 0).text())
# print(rows)
# print(layernames)
ii = 0
if layernames is not None:
for layer_name in layernames:
if (not self.ChkSaveShapefile.isChecked()):
try:
uri = opendata_url + "/collections/"+ str(layer_name) + '/items?f=json'
# print (uri)
ogc_layer = QgsVectorLayer(uri, layer_name)
if (ogc_layer.isValid()):
QgsProject.instance().addMapLayer(ogc_layer)
qgis.utils.iface.zoomToActiveLayer()
# success = qgis.utils.iface.addVectorLayer(uri, layer_name,"OGC API - Features")
ii+=1
self.LblStatus.setText (str(ii)+"/ "+ str(len(layernames)) + " layers added")
percent_complete = ii/len(layernames)*100
self.status.setValue(percent_complete)
message = str(int(percent_complete)) + "%"
self.status.setFormat(message)
except Exception as e:
QMessageBox.critical(self.iface.mainWindow(), "OGC API Feature", str(e))
else:
try:
uri = opendata_url + "/collections/"+ str(layer_name) + '/items?f=' + ogc_format
# print (uri)
filename = outdir + "/"+ str(layer_name).replace(":","_") + ext
ssl._create_default_https_context = ssl._create_unverified_context
#urllib.request.urlretrieve(uri,filename,context=ssl._create_unverified_context())
urllib.request.urlretrieve(uri,filename)
layer = QgsVectorLayer(filename, QFileInfo(filename).baseName(), 'ogr')
layer.dataProvider().setEncoding(u'UTF-8')
if (layer.isValid()):
QgsProject.instance().addMapLayer(layer)
qgis.utils.iface.zoomToActiveLayer()
ii+=1
self.LblStatus.setText (str(ii)+"/ "+ str(len(layernames)) + " layers saved and added")
percent_complete = ii/len(layernames)*100
self.status.setValue(percent_complete)
message = str(int(percent_complete)) + "%"
self.status.setFormat(message)
except Exception as e:
QMessageBox.critical(self.iface.mainWindow(), "OGC API Feature", str(e))
return
class hcmgis_geofabrik_dialog(hcmgis_dialog, Ui_hcmgis_geofabrik_form):
def __init__(self, iface):
hcmgis_dialog.__init__(self, iface)
self.setupUi(self)
self.BtnApplyClose.button(QtWidgets.QDialogButtonBox.Apply).clicked.connect(self.run)
self.BtnOutputFolder.clicked.connect(self.browse_outfile)
self.cboRegion.setStyleSheet("QComboBox {combobox-popup: 0; }") # To enable the setMaxVisibleItems
self.cboCountry.setStyleSheet("QComboBox {combobox-popup: 0; }") # To enable the setMaxVisibleItems
self.cboCountry.setMaxVisibleItems(10)
self.cboCountry.view().setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.cboProvince.setStyleSheet("QComboBox {combobox-popup: 0; }") # To enable the setMaxVisibleItems
self.cboProvince.setMaxVisibleItems(10)
self.cboProvince.view().setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
project = QgsProject.instance()
home_path = project.homePath()
if not home_path:
home_path = os.path.expanduser('~')
self.LinOutputFolder.setText(home_path)
self.cboRegion.addItems(self.region)
self.cboRegion.currentIndexChanged.connect(self.loadcountry)
self.cboRegion.setCurrentIndex(-1)
self.cboCountry.setCurrentIndex(-1)
self.cboCountry.setEnabled(False)
self.cboCountry.currentIndexChanged.connect(self.loadprovince)
self.cboProvince.setEnabled(False)
self.hcmgis_set_status_bar(self.status,self.LblStatus)
##################### Region
region = ['Africa','Antarctica','Asia','Australia and Oceania','Central America','Europe','North America','South America']
region_name = []
for reg in region:
reg_name = reg.replace(' and ','-').replace(' ','-').lower()
region_name.append(reg_name)
##################### Asia
asia = ['Afghanistan','Armenia','Azerbaijan','Bangladesh','Bhutan','Cambodia','China','GCC States','India','Indonesia',\
'Iran','Iraq','Israel and Palestine','Japan','Jordan','Kazakhstan','Kyrgyzstan','Laos','Lebanon','Malaysia, Singapore, and Brunei',\
'Maldives','Mongolia','Myanmar','Nepal','North Korea','Pakistan','Philippines','Russian Federation','South Korea','Sri Lanka',\
'Syria','Taiwan','Tajikistan','Thailand','Turkmenistan','Uzbekistan','Vietnam','Yemen']
asia_name= []
for country in asia:
country_name = country.replace('Israel and Palestine','israel-and-palestine' ).replace('Malaysia, Singapore, and Brunei','malaysia-singapore-brunei').replace('Russian Federation','russia').replace(' ','-').lower()
asia_name.append(country_name)
japan_state = ['Chubu region','Chugoku region','Hokkaido','Kansai region','Kanto region','Kyushu','Shikoku','Tohoku region']
japan_state_name= []
for state in japan_state:
state_name = state.replace(' region','').lower()
japan_state_name.append(state_name)
##################### Africa
africa =['Algeria','Angola','Benin','Botswana','Burkina Faso','Burundi','Cameroon','Canary Islands','Cape Verde','Central African Republic',\
'Chad','Comores','Congo (Republic/Brazzaville)','Congo (Democratic Republic/Kinshasa)','Djibouti','Egypt','Equatorial Guinea','Eritrea','Ethiopia','Gabon',\
'Ghana','Guinea','Guinea-Bissau','Ivory Coast','Kenya','Lesotho','Liberia','Libya','Madagascar','Malawi',\
'Mali','Mauritania','Mauritius','Morocco','Mozambique','Namibia','Niger','Nigeria','Rwanda','Saint Helena, Ascension, and Tristan da Cunha',\
'Sao Tome and Principe','Senegal and Gambia','Seychelles','Sierra Leone','Somalia','South Africa','South Sudan','Sudan','Swaziland',\
'Tanzania','Togo','Tunisia','Uganda','Zambia','Zimbabwe',\
'South Africa (includes Lesotho)'] #special region
africa_name = []
for country in africa:
country_name = country.replace('Congo (Republic/Brazzaville)','congo-brazzaville').replace('Congo (Democratic Republic/Kinshasa)','congo-democratic-republic')\
.replace('South Africa (includes Lesotho)','south-africa-and-lesotho').replace(' ','-').replace(',','').lower()
africa_name.append(country_name)
##################### Australia
australia = ['Australia','Cook Islands','Fiji','Kiribati','Marshall Islands','Micronesia','Nauru','New Caledonia','New Zealand','Niue',\
'Palau','Papua New Guinea','Samoa','Solomon Islands','Tonga','Tuvalu','Vanuatu']
australia_name = []
for country in australia:
country_name = country.replace(' ','-').lower()
australia_name.append(country_name)
##################### Central America
centralamerica= ['bahamas','Belize','Cuba','Guatemala','Haiti and Dominican Republic','Jamaica','Nicaragua']
centralamerica_name = []
for country in centralamerica:
country_name = country.replace('Dominican Republic','domrep').replace(' ','-').lower()
centralamerica_name.append(country_name)
##################### Europe
europe= ['Albania','Andorra','Austria','Azores','Belarus','Belgium','Bosnia-Herzegovina','Bulgaria','Croatia','Cyprus',\
'Czech Republic','Denmark','Estonia','Faroe Islands','Finland','France','Georgia (Eastern Europe)','Germany','Great Britain','Greece',\
'Hungary','Iceland','Ireland and Northern Ireland','Isle of Man','Italy','Kosovo','Latvia','Liechtenstein','Lithuania','Luxembourg',\
'Macedonia','Malta','Moldova','Monaco','Montenegro','Netherlands','Norway','Poland','Portugal','Romania',\
'Russian Federation','Serbia','Slovakia','Slovenia','Spain','Sweden','Switzerland','Turkey','Ukraine (with Crimea)',\
'Alps','Britain and Ireland','Germany, Austria, Switzerland']#special regions
europe_name = []
for country in europe:
country_name = country.replace('Georgia (Eastern Europe)','georgia').replace('Ukraine (with Crimea)','ukraine').replace('Germany, Austria, Switzerland','dach').\
replace('Russian Federation','russia').replace(' ','-').lower()
europe_name.append(country_name)
france_state = ['Alsace','Aquitaine','Auvergne','Basse-Normandie','Bourgogne','Bretagne','Centre','Champagne Ardenne','Corse','Franche Comte',\
'Guadeloupe','Guyane','Haute-Normandie','Ile-de-France','Languedoc-Roussillon','Limousin','Lorraine','Martinique','Mayotte','Midi-Pyrenees',\
'Nord-Pas-de-Calais','Pays de la Loire','Picardie','Poitou-Charentes','Provence Alpes-Cote-d''Azur','Reunion','Rhone-Alpes']
france_state_name= []
for state in france_state:
state_name = state.replace(' ','-').lower()
france_state_name.append(state_name)
germany_state = ['Baden-Wurttemberg','Bayern','Berlin','Brandenburg (mit Berlin)','Bremen','Hamburg','Hessen','Mecklenburg-Vorpommern','Niedersachsen','Nordrhein-Westfalen',\
'Rheinland-Pfalz','Saarland','Sachsen','Sachsen-Anhalt','Schleswig-Holstein','Thuringen']
germany_state_name= []
for state in germany_state:
state_name = state.replace('Brandenburg (mit Berlin)','brandenburg').lower()
germany_state_name.append(state_name)
great_britain_state = ['England','Scotland','Wales']
great_britain_state_name = ['england','scotland','wales']
italy_state = ['Centro', 'Isole', 'Nord-Est', 'Nord-Ovest', 'Sud']
italy_state_name =[]
for state in italy_state:
state_name = state.lower()
italy_state_name.append(state_name)
netherlands_state = ['Drenthe','Flevoland','Friesland','Gelderland','Groningen','Limburg','Noord-Brabant','Noord-Holland','Overijssel','Utrecht',\
'Zeeland','Zuid-Holland']
netherlands_state_name= []
for state in netherlands_state: