-
Notifications
You must be signed in to change notification settings - Fork 0
/
flurstuecks_finder_nrw.py
1726 lines (1610 loc) · 75.5 KB
/
flurstuecks_finder_nrw.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Flurstücksfinder NRW
A QGIS plugin
With this plugin Flurstücke can be searched on a WFS
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2021-03-03
git sha : $Format:%H$
copyright : (C) 2021 by Kreis Viersen
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
try:
from qgis.core import (
Qgis,
QgsBlockingNetworkRequest,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsField,
QgsFields,
QgsGml,
QgsMessageLog,
QgsPalLayerSettings,
QgsProject,
QgsProperty,
QgsPropertyCollection,
QgsTextBufferSettings,
QgsTextFormat,
QgsVectorLayer,
QgsVectorLayerSimpleLabeling,
QgsWkbTypes,
)
from qgis.gui import QgsHighlight, QgsMapToolEmitPoint
from qgis.PyQt import uic
from qgis.PyQt.QtCore import QCoreApplication, QSize, Qt, QUrl, QVariant, pyqtSignal
from qgis.PyQt.QtGui import QColor, QFont, QIcon, QPixmap
from qgis.PyQt.QtNetwork import QNetworkRequest
from qgis.PyQt.QtWidgets import (
QAction,
QApplication,
QDockWidget,
QHeaderView,
QMenu,
QMessageBox,
QTableWidgetItem,
QToolButton,
)
from qgis.utils import iface
import configparser
import hashlib
import json
import os
import re
import sys
import urllib
import webbrowser
from collections import OrderedDict
from io import BytesIO
from lxml import etree
except (ModuleNotFoundError, ImportError) as module_error:
error_string = f"[Flurstücksfinder NRW Fehler]: {module_error.args[0]} - Modul kann nicht importiert werden. Bitte überprüfen Sie, ob dieses Python-Modul installiert ist!"
QgsMessageLog.logMessage(error_string, "Flurstücksfinder NRW", level=Qgis.Critical)
iface.messageBar().pushMessage(error_string, level=Qgis.Critical)
sys.exit(error_string)
# Initialize Qt resources from file resources_rc.py
from .resources_rc import *
from .start_josm import *
qgis_version = Qgis.QGIS_VERSION.split("-")[0]
# For future releases to catch version differences
# QgsMessageLog.logMessage('Nachricht', 'Flurstücksfinder NRW', level=Qgis.Info)
# ---------------------------------------------------------------------------- #
# Class to initialize the plugin GUIs #
# ---------------------------------------------------------------------------- #
# Defines the GUI file for the dock widget
sys.path.append(os.path.dirname(__file__))
FORM_CLASS, _ = uic.loadUiType(
os.path.join(os.path.dirname(__file__), "flurstuecks_finder_nrw_dockwidget_base.ui")
)
class FlurstuecksFinderNRWDockWidget(QDockWidget, FORM_CLASS):
"""Initialize the dockwidget"""
closingPlugin = pyqtSignal()
keyPressed = pyqtSignal(int)
def __init__(self, parent=None):
"""Initializes the GUI of the dock widget"""
super(FlurstuecksFinderNRWDockWidget, self).__init__(parent)
self.setupUi(self)
def keyPressEvent(self, event):
super(FlurstuecksFinderNRWDockWidget, self).keyPressEvent(event)
self.keyPressed.emit(event.key())
def closeEvent(self, event):
# Removes any map highlights that may be present.
if FlurstuecksFinderNRW.highlight and FlurstuecksFinderNRW.highlight2:
iface.mapCanvas().scene().removeItem(FlurstuecksFinderNRW.highlight)
iface.mapCanvas().scene().removeItem(FlurstuecksFinderNRW.highlight2)
self.closingPlugin.emit()
event.accept()
# ---------------------------------------------------------------------------- #
# Class of the actual plugin #
# ---------------------------------------------------------------------------- #
class FlurstuecksFinderNRW:
"""Main plugin class"""
closingPlugin = pyqtSignal()
highlight = None
highlight2 = None
def __init__(self, iface):
"""Ininitalsiert the plugin class"""
# QGIS Interface
self.iface = iface
# Defines a layer variable for later use
self.layer = None
# QGIS map canvas
self.canvas = self.iface.mapCanvas()
# Initializes the plugin directory
self.plugin_dir = os.path.dirname(__file__)
# Initializes the ConfigParser object
self.config = configparser.ConfigParser()
# Initializes the config file
self.config_file = os.path.join(self.plugin_dir, "settings.ini")
# Writes by default the district Viersen as a district in the Config,
# if the file does not exist
if not os.path.isfile(self.config_file):
# Disabled to to issues in QGIS 3.20.1
self.config["DEFAULT"]["nrw"] = "True"
self.config["DEFAULT"]["katasteramt"] = "None"
with open(self.config_file, "w", encoding="UTF-8") as file:
self.config.write(file)
# Initialization of various variables
self.crs = None
self.crs_dict = {}
self.epsg = None
self.geom = None
self.nrw = True
self.extent = None
self.katasteramt = None
self.katasterdaten = None
self.cache_updated = False
self.wfs_prefix = None
# Reads out the config file and sets the variable area to the current value
# current value from the Conig file
self.config.read(self.config_file)
if self.config.has_option("", "nrw"):
self.nrw = self.config["DEFAULT"]["nrw"]
if self.nrw == "True":
self.nrw = True
elif self.nrw == "False":
self.nrw = False
if self.config.has_option("", "katasteramt"):
self.katasteramt = self.config["DEFAULT"]["katasteramt"]
if self.katasteramt == "None":
self.katasteramt = None
else:
self.katasteramt = None
# Initializes the path to the icons
self.icon_path = ":/plugins/flurstuecks_finder_nrw/icons/"
# Initializes the cache directory and creates it if necessary.
self.cache_dir = os.path.join(self.plugin_dir, "cache")
if not os.path.isdir(self.cache_dir):
try:
os.mkdir(self.cache_dir)
except OSError:
print(f"Verzeichnis {self.cache_dir} konnte nicht erstellt werden")
# Initializes a list of 'actions' that will be triggered,
# when the plugin buttons are pressed
self.actions = []
# Initializes a button in the toolbar as a dropdown menu
self.toolbar_button = QToolButton()
self.toolbar_button.setMenu(QMenu())
self.toolbar_button.setPopupMode(QToolButton.MenuButtonPopup)
self.menu = self.toolbar_button.menu()
self.tool_btn_action = self.iface.addToolBarWidget(self.toolbar_button)
# Initialize plugin menu entry with icon
self.menu2 = QMenu(self.tr("&Flurstücksfinder NRW"))
self.menu2.setIcon(QIcon(self.icon_path + "finder.png"))
self.iface.pluginMenu().addMenu(self.menu2)
# At initialization the plugin is not yet active
self.pluginIsActive = False
self.dockwidget = None
# Definition of a mouse click function (returns x and y)
self.mouse_click = QgsMapToolEmitPoint(self.canvas)
self.mouse_click.canvasClicked.connect(
lambda xy: self.SearchFlurstueck("clicked", xy)
)
self.maptool = self.mouse_click
self.maptool.setCursor(Qt.WhatsThisCursor)
# Variable for the first start of the plugin
self.first_start = True
def tr(self, message):
"""Function to translate"""
return QCoreApplication.translate("FlurstuecksFinderNRW", message)
def AddAction(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None,
):
"""Inserts actions into the plugin"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_menu:
self.menu.addAction(action)
self.menu2.addAction(action)
self.actions.append(action)
return action
def initGui(self):
"""Creates the toolbar icons in the QGIS GUI and the dockwidget"""
# Action for opening the normal Flurstück finder GUI
self.AddAction(
icon_path=self.icon_path + "finder.png",
text=self.tr("Flurstücksfinder NRW öffnen"),
callback=self.run,
parent=self.iface.mainWindow(),
)
# Action for retrieving a Flurstück by click
self.AddAction(
icon_path=self.icon_path + "click.png",
text=self.tr("Flurstück mit Klick finden"),
callback=self.SearchFlurstueckClicked,
parent=self.iface.mainWindow(),
)
# Action for showing about message box
self.AddAction(
icon_path=self.icon_path + "info.png",
text=self.tr("Über Flurstücksfinder NRW"),
callback=self.about,
parent=self.iface.mainWindow(),
)
# Sets the default action for the button menu
# Normal search mask as default
default_action = [
a for a in self.actions if a.text() == "Flurstücksfinder NRW öffnen"
][0]
self.toolbar_button.setDefaultAction(default_action)
# Actions and buttons have been added, now
# defines the dock widget as an object
if self.dockwidget is None:
self.dockwidget = FlurstuecksFinderNRWDockWidget()
# Text from Gemarkung combo box into text field
self.dockwidget.cmb_gemarkung_name.activated.connect(
self.MatchComboBoxesTextFields
)
# Text from Gemarkung key combo box into text field
self.dockwidget.cmb_gemarkung_id.activated.connect(
self.MatchComboBoxesTextFields
)
# Text from Fluren combo box into text field
self.dockwidget.cmb_flur_nr.activated.connect(self.MatchComboBoxesTextFields)
# Text from Flurstücke combo box into text field
self.dockwidget.cmb_flurstueck.activated.connect(self.MatchComboBoxesTextFields)
# Actions that will be executed when the index of the
# comboboxes changes (comparison of the name of the
# Gemarkungsname with the Gemarkungs-Schlüssel )
self.dockwidget.cmb_gemarkung_name.currentIndexChanged.connect(
lambda: self.dockwidget.cmb_gemarkung_id.setCurrentIndex(
self.dockwidget.cmb_gemarkung_id.findText(
re.sub(
"[^0-9]", "", self.dockwidget.cmb_gemarkung_name.currentText()
),
Qt.MatchFixedString,
)
)
)
self.dockwidget.cmb_gemarkung_id.currentIndexChanged.connect(
lambda: self.dockwidget.cmb_gemarkung_name.setCurrentIndex(
self.dockwidget.cmb_gemarkung_name.findText(
self.dockwidget.cmb_gemarkung_id.currentText(), Qt.MatchContains
)
)
)
# Actions when the combo boxes are clicked/activated
# When Gemarkung is activated, the combo box for fluren is filled.
self.dockwidget.cmb_katasteramt.currentIndexChanged.connect(self.SetKatasteramt)
self.dockwidget.cmb_katasteramt.currentIndexChanged.connect(
self.FillComboBoxGemarkung
)
self.dockwidget.cmb_gemarkung_name.currentIndexChanged.connect(
self.FillComboBoxFluren
)
self.dockwidget.cmb_flur_nr.currentIndexChanged.connect(
self.FillComboBoxFlurstuecke
)
# Button for Flurstück search via Flurstückkennzeichen (Gemarkung-Flur-Flurstück)
self.dockwidget.btn_suchen_flurstueck_nr.clicked.connect(
lambda: self.SearchFlurstueck("flstkennz", None)
)
# Button for Flurstück search via ALKIS ID
self.dockwidget.btn_suchen_alkis_id.clicked.connect(
lambda: self.SearchFlurstueck("alkisid", None)
)
# Button for Flurstück search via Flurstückkennzeichen
self.dockwidget.btn_suchen_flstkennzlang.clicked.connect(
lambda: self.SearchFlurstueck("flstkennzlang", None)
)
# Search the Flurstück if the last combobox is activated
self.dockwidget.cmb_flurstueck.activated.connect(
lambda: self.SearchFlurstueck("flstkennz", None)
)
# button adds or deletes the Flurstück polygon
self.dockwidget.btn_add_flurstueck.clicked.connect(
lambda: self.AddFlurstueckLayer(self.layer)
)
# button opens the geoportal Niederrhein
self.dockwidget.btn_open_portal.clicked.connect(
lambda: self.OpenBrowser("portal")
)
# button opens JOSM
self.dockwidget.btn_open_josm.clicked.connect(lambda: self.OpenBrowser("josm"))
# button opens JOSM
self.dockwidget.btn_open_id.clicked.connect(lambda: self.OpenBrowser("id"))
# Execute the search when the return key is pressed
self.dockwidget.keyPressed.connect(self.KeyPressed)
self.dockwidget.txt_gemarkung_flur_flurstueck.textChanged.connect(
lambda text: self.TextFieldChanged(
text, self.dockwidget.btn_suchen_flurstueck_nr
)
)
self.dockwidget.txt_alkis_id.textChanged.connect(
lambda text: self.TextFieldChanged(
text, self.dockwidget.btn_suchen_alkis_id
)
)
self.dockwidget.txt_flstkennzlang.textChanged.connect(
lambda text: self.TextFieldChanged(
text, self.dockwidget.btn_suchen_flstkennzlang
)
)
if self.nrw is False:
self.dockwidget.btn_open_portal.setToolTip(
"Öffnet die Flurstücks-Position im Geoportal Niederrhein"
)
else:
self.dockwidget.btn_open_portal.setToolTip(
"Öffnet die Flurstücks-Position in TIM-Online"
)
# QTableWidget custom action when right-clicking with the mouse, calls a function
self.dockwidget.tbl_flurstueck.setContextMenuPolicy(Qt.CustomContextMenu)
self.dockwidget.tbl_flurstueck.customContextMenuRequested.connect(
self.CopyTableCell
)
# ---------------------------------------------------------------------------- #
def onClosePlugin(self):
"""Deletes all items of the plugin when it is closed"""
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
self.first_start = True
self.pluginIsActive = False
def unload(self):
"""Removes the menu items and the buttons"""
for action in self.actions:
self.iface.removePluginMenu(self.tr("&Flurstücksfinder NRW"), action)
self.iface.removeToolBarIcon(action)
self.iface.removeToolBarIcon(self.tool_btn_action)
self.menu2.deleteLater()
def RemoveHighlights(self):
"""This removes previously created map highlights (red markers)"""
if hasattr(FlurstuecksFinderNRW, "highlight"):
self.iface.mapCanvas().scene().removeItem(self.highlight)
self.iface.mapCanvas().scene().removeItem(self.highlight2)
# ---------------------------------------------------------------------------- #
def KeyPressed(self, key):
"""Perform the search action of Return key is pressed"""
# Check whether enter or return key is pressed
if key in [Qt.Key_Return, Qt.Key_Enter]:
if (
len(self.dockwidget.txt_alkis_id.text()) != 0
and self.dockwidget.txt_alkis_id.hasFocus()
):
self.SearchFlurstueck("alkisid", None)
elif (
len(self.dockwidget.txt_gemarkung_flur_flurstueck.text()) != 0
and self.dockwidget.txt_gemarkung_flur_flurstueck.hasFocus()
):
self.SearchFlurstueck("flstkennz", None)
elif (
len(self.dockwidget.txt_flstkennzlang.text()) != 0
and self.dockwidget.txt_flstkennzlang.hasFocus()
):
self.SearchFlurstueck("flstkennzlang", None)
def PushMessage(self, message, level):
self.iface.messageBar().clearWidgets()
self.iface.messageBar().pushMessage(message, level=level, duration=3)
self.iface.mainWindow().repaint()
def ShowMessage(self, art, meldung):
"""Creates a message for the user"""
mb = QMessageBox()
mb.setWindowFlags(Qt.WindowStaysOnTopHint)
if art == "Frage":
mb.setWindowTitle("Frage")
mb.setIcon(QMessageBox.Question)
mb.addButton("Ja", mb.AcceptRole)
mb.addButton("Nein", mb.RejectRole)
elif art == "Fehler":
mb.setWindowTitle("Fehler")
mb.setIcon(QMessageBox.Critical)
mb.addButton("OK", mb.AcceptRole)
elif art == "Warning":
mb.setWindowTitle("Flurstücksfinder NRW Warnung")
mb.setText(f"Es ist ein Fehler aufgetreten!\n\n{meldung}")
mb.setIcon(QMessageBox.Warning)
mb.addButton("Okay", mb.AcceptRole)
elif art == "Info":
mb.setWindowTitle("Flurstücksfinder NRW Info")
mb.setIcon(QMessageBox.Information)
mb.addButton("Okay", mb.AcceptRole)
mb.setText(meldung)
return mb
# ---------------------------------------------------------------------------- #
# Functions for buttons #
# ---------------------------------------------------------------------------- #
def InitRadioButtons(self):
"""Reads out the config file and sets the radio buttons"""
check_button = None
self.dockwidget.rb_group.buttonToggled.connect(self.RadioButtonChanged)
if self.nrw is False:
if self.katasteramt:
check_button = [
b
for b in self.dockwidget.rb_group.buttons()
if b.text() == self.katasteramt
]
self.dockwidget.cmb_katasteramt.setEnabled(False)
else:
check_button = [
b for b in self.dockwidget.rb_group.buttons() if b.text() == "NRW"
]
self.dockwidget.cmb_katasteramt.setEnabled(True)
if check_button is not None:
check_button = check_button[0]
check_button.setChecked(True)
self.dockwidget.rb_group.setExclusive(True)
def RadioButtonChanged(self, button, checked):
"""Checks the setting of the radio buttons
and writes the setting to a config file"""
self.ResetComboBoxes()
self.ResetComboBoxesIndex()
self.ClearTextFields()
if checked is True and button.text() != "NRW":
self.nrw = False
self.katasteramt = button.text()
self.config["DEFAULT"]["nrw"] = "False"
self.config["DEFAULT"]["katasteramt"] = self.katasteramt
self.dockwidget.cmb_katasteramt.setEnabled(False)
self.dockwidget.cmb_katasteramt.setCurrentIndex(-1)
self.dockwidget.id_suchen_gbox.setTitle(f"ID in {self.katasteramt} suchen")
self.dockwidget.flurstueck_suchen_gbox.setTitle(
f"Flurstück in {self.katasteramt} suchen"
)
self.ChangePushButtonsIcons("masterportal")
self.FillComboBoxGemarkung()
elif checked is True and button.text() == "NRW":
self.nrw = True
self.config["DEFAULT"]["nrw"] = "True"
self.dockwidget.cmb_katasteramt.setEnabled(True)
self.dockwidget.id_suchen_gbox.setTitle("ID NRW-weit suchen")
self.dockwidget.flurstueck_suchen_gbox.setTitle(
f"Bitte Katasteramt im Reiter Einstellung wählen"
)
self.ChangePushButtonsIcons("timonline")
self.FillComboBoxKatasteramt()
if checked is True:
self.GetCRS()
if os.path.isfile(self.config_file):
with open(self.config_file, "w+", encoding="UTF-8") as file:
self.config.write(file)
def ChangePushButtonsIcons(self, icon):
"""Depending on whether a Flurstück polygon
has already been added, the icon will be changed"""
if icon == "remove":
iconRemove = QIcon()
iconRemove.addPixmap(QPixmap(os.path.join(self.icon_path, "remove.png")))
self.dockwidget.btn_add_flurstueck.setIcon(iconRemove)
self.dockwidget.btn_add_flurstueck.setIconSize(QSize(25, 25))
self.dockwidget.btn_add_flurstueck.setToolTip(
"Durch Klicken wird das Flurstückpolygon entfernt"
)
elif icon == "add":
iconAdd = QIcon()
iconAdd.addPixmap(QPixmap(os.path.join(self.icon_path, "add.png")))
self.dockwidget.btn_add_flurstueck.setIcon(iconAdd)
self.dockwidget.btn_add_flurstueck.setIconSize(QSize(25, 25))
self.dockwidget.btn_add_flurstueck.setToolTip(
"Durch Klicken wird das Flurstückpolygon hinzugefügt"
)
elif icon == "masterportal":
self.dockwidget.btn_open_portal.setToolTip(
"Öffnet das Flurstück im Geoportal Niederrhein"
)
elif icon == "timonline":
self.dockwidget.btn_open_portal.setToolTip(
"Öffnet das Flurstück in TIM-Online"
)
def EnablePushButtons(self):
"""Activates the push buttons"""
# Flurstücke can only be added if they have been searched for successfully
self.dockwidget.btn_add_flurstueck.setEnabled(True)
# Opens the geoportal Niederhein
self.dockwidget.btn_open_portal.setEnabled(True)
# The Flurstück info is only shown when the Fluurstück was searched for
self.dockwidget.tabWidget.setTabEnabled(1, True)
# JOSM can only be used when a Flurstück has been searched for
josm_app_path, josm_cfg_path = StartJosm(self).josmSearchPath()
if josm_app_path and josm_cfg_path:
if os.path.isfile(josm_app_path) and os.path.isfile(josm_cfg_path):
self.dockwidget.btn_open_josm.setEnabled(True)
# Opens the OSM iD Editor
self.dockwidget.btn_open_id.setEnabled(True)
def DisablePushButtons(self):
"""Disables the push buttons"""
# Flurstücke can only be added if they have been searched for successfully
self.dockwidget.btn_add_flurstueck.setEnabled(False)
# JOSM can only be used when a Flurstück has been searched for
self.dockwidget.btn_open_josm.setEnabled(False)
# Opens the geoportal Niederhein
self.dockwidget.btn_open_portal.setEnabled(False)
# The Flurstück info is only shown when the Flurstück is searched for
self.dockwidget.tabWidget.setTabEnabled(1, False)
# Opens the OSM iD Editor
self.dockwidget.btn_open_id.setEnabled(False)
# Disables to search buttons
self.dockwidget.btn_suchen_alkis_id.setEnabled(False)
self.dockwidget.btn_suchen_flurstueck_nr.setEnabled(False)
self.dockwidget.btn_suchen_flstkennzlang.setEnabled(False)
# ---------------------------------------------------------------------------- #
# Functions for direct interaction with the WFS #
# ---------------------------------------------------------------------------- #
def GetBaseURL(self):
"""Used to select the region to address the respective WFS service"""
base_url = None
wfs_arg = ""
katasteramt = ""
if self.nrw is False:
if self.katasteramt:
katasteramt = self.katasteramt
if "Krefeld" in katasteramt:
wfs_arg = "s"
elif (
"Wesel" in katasteramt
or "Viersen" in katasteramt
or "Kleve" in katasteramt
):
wfs_arg = "k"
katasteramt = katasteramt.replace("Kreis ", "").replace("Stadt ", "")
katasteramt = katasteramt[0:3].lower()
self.wfs_prefix = wfs_arg + katasteramt
base_url = (
"https://geoservices.krzn.de/security-proxy/"
f"services/wfs_{self.wfs_prefix}_alkis_adv_vereinfacht?"
)
elif self.nrw is True:
base_url = "https://www.wfs.nrw.de/geobasis/wfs_nw_alkis_vereinfacht?"
return base_url
def GetCRS(self):
"""Get available CRS from WFS"""
# WFS Request URL
base_url = self.GetBaseURL()
self.crs_dict.clear()
param = {"service": "WFS", "version": "2.0.0", "request": "GetCapabilities"}
if base_url is not None:
url = base_url + urllib.parse.unquote_plus(urllib.parse.urlencode(param))
results = None
request = QgsBlockingNetworkRequest()
request.get(QNetworkRequest(QUrl(url)), True)
reply = request.reply()
if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200:
try:
tree = etree.parse(BytesIO(reply.content()))
root = tree.getroot()
nsmap = root.nsmap
if None in nsmap.keys():
del nsmap[None]
results = root.find(
".//ows:Parameter[@name='srsName']/ows:AllowedValues", nsmap
)
except:
mb = self.ShowMessage(
"Fehler", "Konnte verfügbare KBS vom WFS nicht ermitteln!"
)
mb.setDetailedText(
"Bitte GetCapabilities-Dokument überprüfen:\n\n" + url
)
mb.exec()
if results is not None:
results = results.getchildren()
results = [result.text for result in results]
else:
mb = self.ShowMessage(
"Fehler", "Konnte verfügbare KBS vom WFS nicht ermitteln!"
)
mb.setDetailedText("Die Anfrage an folgende URL schlug fehl:\n\n" + url)
mb.exec()
if results:
for idx, result in enumerate(results):
epsg = result.split("def:crs:")[1].replace("::", ":")
self.crs_dict[idx] = {"uri": result, "epsg": epsg}
def CheckCRS(self):
"""Checks the CRS"""
crs_list = {}
crs = None
# Checks current CRS
crs = QgsProject.instance().crs().authid()
# If a CRS is defined, then it is checked whether this is contained in the list
# of the allowed WFS CRS, if not: error message
if crs and self.crs_dict:
crs_list = [i.get("epsg") for i in self.crs_dict.values()]
if crs in [i.get("epsg") for i in self.crs_dict.values()]:
self.crs = [
i.get("uri") for i in self.crs_dict.values() if i.get("epsg") == crs
][0]
self.epsg = [
i.get("epsg").strip("EPSG:")
for i in self.crs_dict.values()
if i.get("epsg") == crs
][0]
else:
crs_string = "\n".join(crs_list)
mb = self.ShowMessage(
"Info",
f'Ihr derzeitig ausgewähltes KBS "{crs}" ist nicht mit dem Flurstücksfinder NRW kompatibel',
)
mb.setDetailedText("Erlaubte KBS: \n" + crs_string)
mb.exec()
def GetURL(self, filter, **kwargs):
"""Method to create the WFS URL. The arguments are passed to the method
and filters are set according to the arguments"""
# WFS Request URL
self.CheckCRS()
base_url = self.GetBaseURL()
if base_url is not None:
param = {
"service": "WFS",
"version": "2.0.0",
"request": "GetFeature",
"srsname": self.crs,
}
if self.nrw is True:
param["version"] = "1.1.0"
if filter == "flurstuecke":
if self.nrw is False:
param["typename"] = f"gis:{self.wfs_prefix}_alkis_adv_flurstueckpkt"
param["propertyname"] = "FLSTNRZAE,FLSTNRNEN,FLSTKENNZ"
else:
param["typename"] = "ave:FlurstueckPunkt"
param["propertyname"] = "ave:flstnrnen"
flur_id = None
gem_nr = kwargs["gem_id"]
flur_nr = kwargs["flur_nr"]
if gem_nr and flur_nr:
flur_nr = flur_nr.zfill(3)
gem_id = "05" + gem_nr
flur_id = gem_id + flur_nr
if flur_id:
if self.nrw is False:
param["filter"] = (
"<Filter>"
"<PropertyIsEqualTo>"
"<ValueReference>FLURSCHL</ValueReference>"
f"<Literal>{flur_id}</Literal>"
"</PropertyIsEqualTo>"
"</Filter>"
)
else:
param["filter"] = (
'<Filter xmlns="http://www.opengis.net/ogc" '
'xmlns:ave="http://repository.gdi-de.org/schemas/adv/produkt/alkis-vereinfacht/2.0">'
"<And>"
"<PropertyIsEqualTo>"
"<PropertyName>ave:gemaschl</PropertyName>"
f"<Literal>{gem_id}</Literal>"
"</PropertyIsEqualTo>"
"<PropertyIsEqualTo>"
"<PropertyName>ave:flurschl</PropertyName>"
f"<Literal>{flur_id}</Literal>"
"</PropertyIsEqualTo>"
"</And>"
"</Filter>"
)
elif filter == "oid":
oid = kwargs["id"]
if self.nrw is False:
param["typename"] = f"gis:{self.wfs_prefix}_alkis_adv_flurstueck"
param["filter"] = (
"<Filter>"
"<PropertyIsEqualTo>"
"<ValueReference>IDFLURST</ValueReference>"
f"<Literal>{oid}</Literal>"
"</PropertyIsEqualTo>"
"</Filter>"
)
else:
param["typename"] = "ave:Flurstueck"
param["Filter"] = (
'<Filter xmlns="http://www.opengis.net/ogc" '
'xmlns:ave="http://repository.gdi-de.org/schemas/adv/produkt/alkis-vereinfacht/2.0">'
"<PropertyIsEqualTo>"
"<PropertyName>ave:idflurst</PropertyName>"
f"<Literal>{oid}</Literal>"
"</PropertyIsEqualTo>"
"</Filter>"
)
elif filter == "flstkennz":
flstkennz = kwargs["id"]
if self.nrw is False:
param["typename"] = f"gis:{self.wfs_prefix}_alkis_adv_flurstueck"
param["filter"] = (
"<Filter>"
"<PropertyIsEqualTo>"
"<ValueReference>FLSTKENNZ</ValueReference>"
f"<Literal>{str(flstkennz)}</Literal>"
"</PropertyIsEqualTo>"
"</Filter>"
)
else:
param["typename"] = "ave:Flurstueck"
param["filter"] = (
'<Filter xmlns="http://www.opengis.net/ogc" '
'xmlns:ave="http://repository.gdi-de.org/schemas/adv/produkt/alkis-vereinfacht/2.0">'
"<PropertyIsEqualTo>"
"<PropertyName>ave:flstkennz</PropertyName>"
f"<Literal>{str(flstkennz)}</Literal>"
"</PropertyIsEqualTo>"
"</Filter>"
)
elif filter == "clicked":
x, y = kwargs["x"], kwargs["y"]
if self.nrw is False:
param["typename"] = f"gis:{self.wfs_prefix}_alkis_adv_flurstueck"
if x and y:
param["filter"] = (
"<fes:Filter>"
"<fes:Intersects>"
"<fes:ValueReference>GEOMETRY</fes:ValueReference>"
f'<gml:Point srsName="{self.crs}">'
f"<gml:coordinates>{x},{y}</gml:coordinates>"
"</gml:Point>"
"</fes:Intersects>"
"</fes:Filter>"
)
else:
param["typename"] = "ave:Flurstueck"
if x and y:
param["filter"] = (
"<Filter "
'xmlns="http://www.opengis.net/ogc" '
'xmlns:ave="http://repository.gdi-de.org/schemas/adv/produkt/alkis-vereinfacht/2.0" '
'xmlns:fes="http://www.opengis.net/fes/2.0" '
'xmlns:gml="http://www.opengis.net/gml">'
"<Intersects>"
"<PropertyName>ave:geometrie</PropertyName>"
f'<gml:Point srsName="{self.crs}">'
f"<gml:coordinates>{x},{y}</gml:coordinates>"
"</gml:Point>"
"</Intersects>"
"</Filter>"
)
url = base_url + urllib.parse.unquote_plus(urllib.parse.urlencode(param))
return url
def SetKatasteramt(self):
"""If NRW is activated the Kommune is set by the current text of the combobox"""
# if idx != -1 and self.nrw is True and self.first_start is False:
if len(self.dockwidget.cmb_katasteramt) > 1:
self.katasteramt = self.dockwidget.cmb_katasteramt.currentText()
self.dockwidget.flurstueck_suchen_gbox.setTitle(
f"Flurstück in {self.katasteramt} suchen"
)
if self.katasteramt:
self.config["DEFAULT"]["katasteramt"] = self.katasteramt
with open(self.config_file, "w+", encoding="UTF-8") as file:
self.config.write(file)
def GetFlurstuecke(self):
"""Queries Flurstücke from WFS and saves them to a dict"""
gem = self.dockwidget.cmb_gemarkung_id.currentText()
flur = self.dockwidget.cmb_flur_nr.currentText()
url = self.GetURL(filter="flurstuecke", gem_id=gem, flur_nr=flur)
flurstuecke = {}
flurstuecke_layer = None
if url is not None:
if self.nrw is False:
fieldnames = ["FLSTNRZAE", "FLSTNRNEN", "FLSTKENNZ"]
typename = f"gis:{self.wfs_prefix}_alkis_adv_flurstueckpkt"
geometry = "GEOMETRY"
else:
fieldnames = ["flstnrzae", "flstnrnen", "flstkennz"]
typename = "ave:FlurstueckPunkt"
geometry = "geometrie"
fields = QgsFields()
for fieldname in fieldnames:
fields.append(QgsField(fieldname, QVariant.String, "", 100, 0))
gml = None
gml = QgsGml(typename, geometry, fields)
wfs_request = gml.getFeaturesUri(url)
parsed_features = gml.featuresMap()
if wfs_request[0] == 0:
flurstuecke_layer = QgsVectorLayer(
f"point?crs=EPSG:{self.epsg}", "flurstuecke_layer", "memory"
)
flurstuecke_layer_data_prov = flurstuecke_layer.dataProvider()
flurstuecke_layer_data_prov.addAttributes(fields.toList())
flurstuecke_layer.updateFields()
for i in range(len(parsed_features)):
flurstuecke_layer_data_prov.addFeature(parsed_features[i])
flurstuecke_layer.commitChanges()
flurstuecke_layer.updateExtents()
if flurstuecke_layer is not None:
if flurstuecke_layer.isValid():
features = flurstuecke_layer.getFeatures()
for idx, flurstueck in enumerate(features):
flst_zae = flurstueck[fieldnames[0]]
flstkennz = flurstueck[fieldnames[2]]
flst_nen = ""
flstnr = flst_zae
if flurstuecke_layer.fields().indexFromName(fieldnames[1]) != -1:
if flurstueck[fieldnames[1]]:
flst_nen = "/" + str(flurstueck[fieldnames[1]])
flstnr = flst_zae + flst_nen
flurstuecke[idx] = {
"Flurstückkennzeichen": flstkennz,
"Flurstuecksnummer": flstnr,
}
return flurstuecke
# ---------------------------------------------------------------------------- #
# Functions around comboboxes and textfields #
# ---------------------------------------------------------------------------- #
def FillComboBoxKatasteramt(self):
"""Fills the katasteramt combobox"""
katasteraemter = None
if self.nrw is True:
if len(self.dockwidget.cmb_katasteramt) == 0:
if self.katasterdaten:
katasteraemter = self.katasterdaten.keys()
if katasteraemter:
self.dockwidget.cmb_katasteramt.blockSignals(True)
self.dockwidget.cmb_katasteramt.clear()
self.dockwidget.cmb_katasteramt.addItems(katasteraemter)
self.dockwidget.cmb_katasteramt.setCurrentIndex(-1)
self.dockwidget.cmb_katasteramt.blockSignals(False)
def FillComboBoxGemarkung(self):
"""Fills the combo boxes according to the arguments"""
self.dockwidget.cmb_gemarkung_name.clear()
self.dockwidget.cmb_gemarkung_id.clear()
self.ClearTextFields()
gemarkungen = None
if self.nrw is True and self.dockwidget.cmb_katasteramt.currentIndex() != -1:
self.katasteramt = self.dockwidget.cmb_katasteramt.currentText()
elif (
self.nrw is False
and self.dockwidget.rb_group.checkedButton().text() != "NRW"
):
self.katasteramt = self.dockwidget.rb_group.checkedButton().text()
else:
self.katasteramt = None
if self.katasteramt and self.katasterdaten:
gemarkungen = self.katasterdaten.get(self.katasteramt.replace("Stadt ", ""))
gemarkungen_name = gemarkungen.keys()
gemarkungen_ids = sorted(
[i.get("schluessel") for i in gemarkungen.values()]
)
self.dockwidget.cmb_gemarkung_name.blockSignals(True)
self.dockwidget.cmb_gemarkung_id.blockSignals(True)
self.dockwidget.cmb_gemarkung_name.addItems(gemarkungen_name)
self.dockwidget.cmb_gemarkung_id.addItems(gemarkungen_ids)
self.dockwidget.cmb_gemarkung_name.setCurrentIndex(-1)
self.dockwidget.cmb_gemarkung_id.setCurrentIndex(-1)
self.dockwidget.cmb_gemarkung_name.blockSignals(False)
self.dockwidget.cmb_gemarkung_id.blockSignals(False)
def FillComboBoxFluren(self):
"""Fills the combobox of the flur id"""
self.dockwidget.cmb_flur_nr.clear()
self.dockwidget.cmb_flur_nr.clear()
fluren = None
if self.nrw is True and self.dockwidget.cmb_katasteramt.currentIndex() != -1:
self.katasteramt = self.dockwidget.cmb_katasteramt.currentText()
elif (
self.nrw is False
and self.dockwidget.rb_group.checkedButton().text() != "NRW"
):
self.katasteramt = self.dockwidget.rb_group.checkedButton().text()
else:
self.katasteramt = None
gemarkung = self.dockwidget.cmb_gemarkung_name.currentText()
if self.katasterdaten and gemarkung and self.katasteramt:
fluren = (
self.katasterdaten.get(self.katasteramt.replace("Stadt ", ""))
.get(gemarkung)
.get("fluren")
)
self.dockwidget.cmb_flur_nr.blockSignals(True)
self.dockwidget.cmb_flur_nr.clear()
self.dockwidget.cmb_flurstueck.clear()
self.dockwidget.cmb_flur_nr.addItems(fluren)
self.dockwidget.cmb_flur_nr.setCurrentIndex(-1)
self.dockwidget.cmb_flur_nr.blockSignals(False)
def FillComboBoxFlurstuecke(self):
"""Fills the Flurstücknummer combobox"""
self.dockwidget.cmb_flurstueck.clear()
flurstuecke = {}
flurstuecke_nr = []
if self.dockwidget.cmb_flur_nr.currentIndex() != -1:
# Obtain the Flurstück data from the WFS
flurstuecke = self.GetFlurstuecke()