Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[nowość] PolaMap Lite - pobieranie danych PRNG #25

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
568 changes: 568 additions & 0 deletions Searcher/layer_style/obiekt_PRNG.qml

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions giap_dynamic_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from qgis.utils import iface
from qgis.gui import QgsMapTool

from .prng_tool import PRNGTool
from .OrtoTools import OrtoAddingTool
from .QuickPrint import PrintMapTool
from .SectionManager.CustomSectionManager import CustomSectionManager
Expand Down Expand Up @@ -865,6 +866,10 @@ def set_custom_action(self) -> None:
area_length_tool = QgsMapTool(iface.mapCanvas())
area_length_tool.setAction(main_widget.area_length_action)
self.tbut.setDefaultAction(main_widget.area_length_action)
if oname == "giapPRNG":
self.tbut.setToolTip(tr("PRNG Tool"))
self.prng_tool = PRNGTool(self)
self.tbut.clicked.connect(self.prng_tool.run)

self.tbut.setIcon(icon)

Expand Down
1 change: 1 addition & 0 deletions giap_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def __init__(self, iface: iface) -> None:
self.searcher = SearcherTool(self.main_widget, self.iface)
self.sett = QgsSettings()


self.style_manager = StyleManager(self)
self.print_map_tool = PrintMapTool(self.iface)
self.iface.projectRead.connect(self.projekt_wczytany)
Expand Down
Binary file added icons/giapPRNG.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
177 changes: 177 additions & 0 deletions prng_tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import os

import requests
import json
from qgis.PyQt import QtWidgets, uic, QtCore
from qgis.core import QgsVectorLayer, QgsProject, QgsFeature, QgsGeometry, QgsPointXY, QgsFields, QgsField
from qgis.utils import iface
from qgis.PyQt.QtCore import QTimer
from qgis.PyQt.QtWidgets import QApplication, QProgressDialog


class PRNGTool(QtWidgets.QDialog):
def __init__(self, parent=None) -> None:
"""Constructor."""
super(PRNGTool, self).__init__(parent)
ui_file = os.path.join(os.path.dirname(__file__), 'prng_tool.ui')
uic.loadUi(ui_file, self)

self.setWindowModality(QtCore.Qt.ApplicationModal)
self.setMinimumSize(678, 202)
self.setMaximumSize(678, 202)
self.setWindowOpacity(1.0)

self.SzukajButton.clicked.connect(self.search_location)
self.ObiektButton.clicked.connect(self.add_selected_object_to_layer)
self.results_data = {}
self.listView.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)

def run(self):
self.show()
self.raise_()
self.activateWindow()

def search_location(self):
location_name = self.lineEdit.text()
if not location_name:
QtWidgets.QMessageBox.warning(self, "Błąd", "Proszę podać nazwę lokalizacji.")
return

url = f"http://services.gugik.gov.pl/uug/?request=GetLocation&location={location_name}"

progress_dialog = QProgressDialog("Łączenie", "Anuluj", 0, 100, self)
progress_dialog.setWindowTitle("Proszę czekać")
progress_dialog.setWindowModality(QtCore.Qt.WindowModal)
progress_dialog.setFixedWidth(300)
progress_dialog.setFixedHeight(100)
progress_dialog.setCancelButton(None)
progress_dialog.show()
progress_dialog.setValue(0)
QApplication.sendPostedEvents()
QApplication.processEvents()

try:
response = requests.get(url)
response.raise_for_status()
data = response.json()

self.results_data.clear()
model = QtCore.QStringListModel(self.listView)
model.setStringList([])
self.listView.setModel(model)

if data["found objects"] == 0:
url = f"http://services.gugik.gov.pl/uug/?request=GetAddress&location={location_name}"
response = requests.get(url)
response.raise_for_status()
data = response.json()
if data["found objects"] == 0:
progress_dialog.setValue(100)
QApplication.processEvents()
QtWidgets.QMessageBox.information(self, "Wynik", "Nie znaleziono obiektów.")
return

for key, value in data["results"].items():
self.results_data[key] = {
"name": value["city"], "type": "miasto", "voivodeship": value["voivodeship"], "county": value["county"],
"commune": value["commune"], "class": "", "status": "", "x": value["x"], "y": value["y"], "geometry_wkt": value["geometry_wkt"]
}
else:
self.results_data = data["results"]

items = []
for key, value in self.results_data.items():
items.append(f"{value['name']} ( {value['type']}, {value['voivodeship']}, {value['county']} )")

model.setStringList(items)
self.listView.setModel(model)
progress_dialog.setValue(100)
QApplication.processEvents()

except requests.RequestException as e:
progress_dialog.setValue(100)
QApplication.processEvents()
QtWidgets.QMessageBox.critical(self, "Błąd", f"Błąd w zapytaniu: {e}")
except ValueError:
progress_dialog.setValue(100)
QApplication.processEvents()
QtWidgets.QMessageBox.critical(self, "Błąd", "Nieprawidłowa odpowiedź serwera.")

def add_selected_object_to_layer(self):
selected_index = self.listView.currentIndex()
if not selected_index.isValid():
QtWidgets.QMessageBox.warning(self, "Błąd", "Proszę wybrać obiekt z listy.")
return

selected_text = selected_index.data()
coordinates = None
attributes = []
for key, value in self.results_data.items():
if f"{value['name']} ( {value['type']}, {value['voivodeship']}, {value['county']} )" == selected_text:
coordinates = value['geometry_wkt']
attributes = [value['name'], value['type'], value['voivodeship'], value['county'], value['commune'],
value['class'], value['status'], value['x'], value['y']]
break

if coordinates:
x = attributes[-2]
y = attributes[-1]
existing_features = self.find_features_by_coordinates(x, y)
if existing_features:
self.zoom_to_feature(existing_features[0])
self.close()
return

layer = self.get_layer("MultiPoint?crs=epsg:2180&index=yes", "UUG_obiekty_fizjograficzne", "")
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromWkt(coordinates))
feature.setAttributes(attributes)
layer.dataProvider().addFeature(feature)
layer.updateExtents()
QgsProject.instance().addMapLayer(layer)
self.zoom_to_feature(feature)
self.close()
else:
QtWidgets.QMessageBox.warning(self, "Błąd", "Nie udało się uzyskać koordynatów.")

def get_layer(self, org: str, obj_type: str, qml: str) -> QgsVectorLayer:
layer = QgsProject.instance().mapLayersByName(obj_type)
if layer:
return layer[0]

layer = QgsVectorLayer(org, obj_type, 'memory')
fields = QgsFields()
fields.append(QgsField("name", QtCore.QVariant.String))
fields.append(QgsField("type", QtCore.QVariant.String))
fields.append(QgsField("voivodeship", QtCore.QVariant.String))
fields.append(QgsField("county", QtCore.QVariant.String))
fields.append(QgsField("commune", QtCore.QVariant.String))
fields.append(QgsField("class", QtCore.QVariant.String))
fields.append(QgsField("status", QtCore.QVariant.String))
fields.append(QgsField("x", QtCore.QVariant.String))
fields.append(QgsField("y", QtCore.QVariant.String))
layer.dataProvider().addAttributes(fields)
layer.updateFields()
direc = os.path.dirname(__file__)
layer.loadNamedStyle(os.path.join(direc, 'Searcher', 'layer_style', 'obiekt_PRNG.qml'))
return layer

def change_scale(self, bbox):
iface.mapCanvas().zoomToFeatureExtent(bbox)
iface.mapCanvas().zoomScale(1000)

def zoom_to_feature(self, feature: QgsFeature):
self.timer = QTimer()
self.timer.setSingleShot(True)
self.timer.setInterval(200)
self.timer.timeout.connect(lambda: self.change_scale(feature.geometry().boundingBox()))
self.timer.start()

def find_features_by_coordinates(self, x, y):
layer = self.get_layer("MultiPoint?crs=epsg:2180&index=yes", "UUG_obiekty_fizjograficzne", "")
feats = [f for f in layer.getFeatures() if f.attribute('x') == x and f.attribute('y') == y]
return feats
82 changes: 82 additions & 0 deletions prng_tool.ui
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>678</width>
<height>202</height>
</rect>
</property>
<property name="windowTitle">
<string>Wyszukaj obiekt z PRNG</string>
</property>
<property name="windowOpacity">
<double>0.000000000000000</double>
</property>
<widget class="QWidget" name="verticalLayoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>651</width>
<height>186</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Podaj nazwę</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item>
<widget class="QPushButton" name="SzukajButton">
<property name="text">
<string>Szukaj</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Wyniki:</string>
</property>
</widget>
</item>
<item>
<widget class="QListView" name="listView">
<property name="enabled">
<bool>true</bool>
</property>
</widget>
</item>
<item alignment="Qt::AlignRight">
<widget class="QPushButton" name="ObiektButton">
<property name="minimumSize">
<size>
<width>120</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>Przybliż do obiektu</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
1 change: 1 addition & 0 deletions resources.qrc
Original file line number Diff line number Diff line change
Expand Up @@ -138,5 +138,6 @@
<file>icons/scripts.png</file>
<file>icons/zglaszaj_awarie.png</file>
<file>icons/admin_tools.png</file>
<file>icons/giapPRNG.png</file>
</qresource>
</RCC>
18 changes: 14 additions & 4 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ def __init__(self, parent):

def sizeHint(self, option, index):
return QtCore.QSize(
QtGui.QTextDocument(index.model().data(index)).idealWidth(), 30)
int(QtGui.QTextDocument(index.model().data(index)).idealWidth()), 30)

def paint(self, painter, option, index):
painter.save()
Expand Down Expand Up @@ -535,6 +535,14 @@ def paint(self, painter, option, index):
]
},

{
'label': tr('Dodatki'),
'id': 'Dodatki',
'btn_size': 30,
'btns': [
['giapPRNG', 0, 0],
]
},
{
'label': tr('Geoprocessing Tools'),
'id': 'Geoprocessing Tools',
Expand Down Expand Up @@ -950,7 +958,7 @@ def paint(self, painter, option, index):
GIAP_CUSTOM_TOOLS = ['GIAP Tools', 'Vector digitization', 'Measurement',
'Project', 'Attributes', 'Advanced attributes',
'Selection', 'Navigation', 'Add Layer', 'Create Layer',
'Prints']
'Prints', 'Dodatki']
TOOLS_HEADERS = [
'Sections',
'GIAP sections',
Expand Down Expand Up @@ -1237,15 +1245,17 @@ def paint(self, painter, option, index):
'mActionShowAlignRasterTool': 'mActionShowAlignRasterTool.png',
'mActionNewMemoryLayer': 'mActionNewMemoryLayer.png',
'mActionSaveProjectAs': 'mActionSaveProjectAs.png',
'window_icon': 'giap_logo.png'
'window_icon': 'giap_logo.png',
'giapPRNG': 'giapPRNG.png'
}

custom_label_dict = {
'giapWMS': "Add WMS/WMTS services",
'giapCompositions': "Composition settings",
"giapQuickPrint": "Map quick print",
"giapMyPrints": "My Prints",
"giapAreaLength": 'Area and length'
"giapAreaLength": 'Area and length',
'giapPRNG': 'PRNG Tool'
}

max_ele_nazwy = 4
Expand Down