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 geometrii działek i punktów adreso… #28

Open
wants to merge 1 commit 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
2 changes: 1 addition & 1 deletion Searcher/layer_style/PUNKT_ADRESOWY.qml
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@
<rules key="{ecf1a5bf-47b7-4d46-b080-a267d3504529}">
<rule key="{29338173-0835-462c-81e7-e70e7d92510b}" scalemaxdenom="1000" scalemindenom="1">
<settings calloutType="simple">
<text-style fieldName=" &quot;street&quot; ||' '||&quot;number&quot;" capitalization="0" fontItalic="0" previewBkgrdColor="255,255,255,255" textOrientation="horizontal" namedStyle="Bold" fontLetterSpacing="0" fontSizeMapUnitScale="3x:0,0,0,0,0,0" fontWeight="75" blendMode="0" useSubstitutions="0" fontFamily="MS Shell Dlg 2" fontSize="3" fontStrikeout="0" fontUnderline="0" isExpression="1" textColor="255,255,255,255" fontSizeUnit="MapUnit" fontWordSpacing="0" fontKerning="1" textOpacity="1" multilineHeight="1" allowHtml="0">
<text-style fieldName="CASE WHEN &quot;street&quot; IS NULL THEN &quot;city&quot; || ' ' || &quot;number&quot; ELSE &quot;street&quot; || ' ' || &quot;number&quot; || ', ' || &quot;city&quot; END" capitalization="0" fontItalic="0" previewBkgrdColor="255,255,255,255" textOrientation="horizontal" namedStyle="Bold" fontLetterSpacing="0" fontSizeMapUnitScale="3x:0,0,0,0,0,0" fontWeight="75" blendMode="0" useSubstitutions="0" fontFamily="MS Shell Dlg 2" fontSize="3" fontStrikeout="0" fontUnderline="0" isExpression="1" textColor="255,255,255,255" fontSizeUnit="MapUnit" fontWordSpacing="0" fontKerning="1" textOpacity="1" multilineHeight="1" allowHtml="0">
<text-buffer bufferDraw="1" bufferColor="0,0,0,255" bufferSizeUnits="MapUnit" bufferSizeMapUnitScale="3x:0,0,0,0,0,0" bufferJoinStyle="64" bufferBlendMode="0" bufferSize="1" bufferNoFill="0" bufferOpacity="1"/>
<text-mask maskJoinStyle="128" maskOpacity="1" maskedSymbolLayers="" maskEnabled="0" maskType="0" maskSizeUnits="MM" maskSizeMapUnitScale="3x:0,0,0,0,0,0" maskSize="0"/>
<background shapeRadiiUnit="MM" shapeOffsetX="0" shapeBorderWidthUnit="MM" shapeType="0" shapeSizeMapUnitScale="3x:0,0,0,0,0,0" shapeOffsetUnit="MM" shapeRotationType="0" shapeBlendMode="0" shapeSVGFile="" shapeRadiiX="0" shapeBorderWidth="0" shapeBorderColor="128,128,128,255" shapeSizeUnit="MM" shapeOffsetMapUnitScale="3x:0,0,0,0,0,0" shapeRadiiMapUnitScale="3x:0,0,0,0,0,0" shapeRotation="0" shapeOffsetY="0" shapeSizeType="0" shapeSizeX="0" shapeDraw="0" shapeBorderWidthMapUnitScale="3x:0,0,0,0,0,0" shapeRadiiY="0" shapeFillColor="255,255,255,255" shapeJoinStyle="64" shapeOpacity="1" shapeSizeY="0">
Expand Down
12 changes: 10 additions & 2 deletions Searcher/searchAddress.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
from qgis.utils import iface

from ..utils import tr, add_map_layer_to_group, search_group_name, project
################################################################
from qgis.core import QgsField, QgsFeature, QgsGeometry
################################################################


class SearchAddress:
Expand All @@ -30,7 +33,7 @@ def __init__(self):
QgsField("number", QVariant.String, len=20),
QgsField("simc", QVariant.String, len=30),
QgsField("street", QVariant.String, len=250),
QgsField("stret_accuracy", QVariant.String, len=10),
QgsField("street_accuracy", QVariant.String, len=10),
QgsField("teryt", QVariant.String, len=20),
QgsField("ulic", QVariant.String, len=30),
QgsField("x", QVariant.Double, "double", 10, 4),
Expand Down Expand Up @@ -120,6 +123,8 @@ def process_results(self) -> Union[
return False, tr('Check log, problems occured.')
fnm = lyr.dataProvider().fieldNameMap()
feats = []


if 'only exact numbers' in self.jres.keys(): # if jezeli znajdzie dokladnie ten adres
exact_adr = self.jres['results'][
'1'] # poprzednia metoda zapelniala warstwe wszystkim co znalazla
Expand Down Expand Up @@ -148,7 +153,7 @@ def process_results(self) -> Union[
feats.append(feat)

return True, feats

def zoom_to_feature(self, layer: str) -> None:
layer = project.mapLayersByName(layer)[0]
iface.mapCanvas().zoomScale(500)
Expand All @@ -167,3 +172,6 @@ def add_feats(self, feats: QgsFeature) -> Union[bool, None]:
lyr.dataProvider().addFeatures(feats)
self.zoom_to_feature(obj_type)
return True



14 changes: 9 additions & 5 deletions Searcher/searchParcel.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,14 @@ def fetch_parcel(self, teryt: str) -> bool:
'geom_wkt,teryt,voivodeship,county,region,commune,parcel'
return self.fetch()

def fetch(self) -> bool:
if '- gmina' in self.params or '- miasto' in self.params:
flag = self.params.find('-')
self.params = self.params[0:flag]
url = f'https://uldk.gugik.gov.pl/?{self.params}'
def fetch(self, url=None) -> bool:
################################
if url is None:
################################
if '- gmina' in self.params or '- miasto' in self.params:
flag = self.params.find('-')
self.params = self.params[0:flag]
url = f'https://uldk.gugik.gov.pl/?{self.params}'
self.responce = []
try:
with urlopen(url, timeout=19) as url_handler:
Expand Down Expand Up @@ -150,3 +153,4 @@ def _create_feature(self, row: str) -> QgsFeature:
feat['pow_graf'] = geom.area()

return feat
################################################################
172 changes: 171 additions & 1 deletion Searcher/searchTool.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,21 @@
from qgis.core import QgsVectorLayer
from qgis.utils import iface
from typing import Union, Dict, List
########################################################################
from qgis.core import QgsField, QgsFeature, QgsGeometry, QgsPointXY, QgsMapLayer
from PyQt5.QtCore import QVariant

from qgis.gui import QgsMapToolEmitPoint
from urllib.request import urlopen
from qgis.core import Qgis
import os
########################################################################

from .searchAddress import SearchAddress
from .searchParcel import FetchULDK, ParseResponce
from ..utils import tr, CustomMessageBox, add_map_layer_to_group, \
ProgressDialog, identify_layer_in_group, root, WFS_PRG
ProgressDialog, identify_layer_in_group, root, WFS_PRG, search_group_name, project



class SearcherTool:
Expand All @@ -35,7 +45,18 @@ def __init__(self, dock, iface):
self.gmi_changed)
self.dock.lineEdit_parcel.returnPressed.connect(
self.search_parcel)
################################################################################
self.dock.buttonParcelNr.clicked.connect(self.handle_parcel_button_click)
self.dock.buttonAdress.clicked.connect(self.handle_address_button_click)
self._pointTool = None
self._previousTool = None
self.clicked_x = None
self.clicked_y = None

################################################################################
self.fetch_voivodeship()


# TIMER
self.typing_timer = QTimer()
self.typing_timer.setSingleShot(True)
Expand Down Expand Up @@ -345,3 +366,152 @@ def search_parcel(self) -> None:
pr = ParseResponce()
pr.get_layer()
pr.parse_responce(feULDK.responce)

############################################################################

def handle_parcel_button_click(self):
if self._pointTool is not None:
self.iface.mapCanvas().unsetMapTool(self._pointTool)
self._pointTool = None
# Store the previous tool in use by the user
canvas = self.iface.mapCanvas()
self._previousTool = canvas.mapTool()
# Set the tool and onClick callback
self._pointTool = PrintClickedPoint(canvas, self)
canvas.setMapTool(self._pointTool)


def handle_address_button_click(self):
if self._pointTool is not None:
self.iface.mapCanvas().unsetMapTool(self._pointTool)
self._pointTool = None
canvas = self.iface.mapCanvas()
self._previousTool = canvas.mapTool()
self._pointTool = PrintClickedPoint(canvas, self, mode='address')
canvas.setMapTool(self._pointTool)



def on_point_callback(self, point, mode='parcel'):
self.clicked_x = round(point.x(), 2)
self.clicked_y = round(point.y(), 2)
if mode == 'parcel':
self.fetch_parcel_by_xy()
elif mode == 'address':
self.fetch_address_by_xy()


def fetch_address_by_xy(self):
if self.clicked_x is not None and self.clicked_y is not None:
url = f'https://services.gugik.gov.pl/uug/?request=GetAddressReverse&location=POINT({self.clicked_x} {self.clicked_y})&srid=2180'
print(url)
try:
response = requests.get(url, verify = False)
response.raise_for_status()
data = response.json()
if 'results' in data and data['results']:
first_key = list(data['results'].keys())[0]
address = data['results'][first_key]

self.add_address_point(address)

else:
self.iface.messageBar().pushMessage("Error", "No address found", level=Qgis.Warning)
except requests.RequestException as e:
self.iface.messageBar().pushMessage("Error", str(e), level=Qgis.Critical)
else:
self.iface.messageBar().pushMessage("Error", "Invalid coordinates", level=Qgis.Critical)

def add_address_point(self, address):
self.flds = [
QgsField('accuracy', QVariant.String, len=10),
QgsField("city", QVariant.String, len=150),
QgsField("city_accuracy", QVariant.String, len=10),
QgsField("citypart", QVariant.String, len=150),
QgsField("code", QVariant.String, len=6),
QgsField("jednostka", QVariant.String, len=250),
QgsField("number", QVariant.String, len=20),
QgsField("simc", QVariant.String, len=30),
QgsField("street", QVariant.String, len=250),
QgsField("street_accuracy", QVariant.String, len=10),
QgsField("teryt", QVariant.String, len=20),
QgsField("ulic", QVariant.String, len=30),
QgsField("x", QVariant.Double, "double", 10, 4),
QgsField("y", QVariant.Double, "double", 10, 4),
]
# Check the existing layer
org = 'MultiPoint?crs=epsg:2180&index=yes'
obj_type = 'UUG_pkt'
qml = os.path.join('layer_style', 'PUNKT_ADRESOWY.qml')
layer = self.get_layer_data(org, obj_type, qml)


# Create a feature and set its attributes
fet = QgsFeature()
geometry = QgsGeometry.fromPointXY(QgsPointXY(self.clicked_x, self.clicked_y))
fet.setGeometry(geometry)
fet.setFields(layer.fields())

# Populate fields based on address data
for field in self.flds:
field_name = field.name()
if field_name in layer.fields().names(): # Ensure the field exists in the layer
if field_name in address:
# Check if the value is "null" and replace it with "Null"
value = address[field_name]
if value == "null":
value = None
fet.setAttribute(field_name, value)
else:
fet.setAttribute(field_name, None) # Set default value to None

# Add the feature to the layer
pr = layer.dataProvider()
pr.addFeature(fet)
layer.updateExtents()
layer.triggerRepaint()


def get_layer_data(self, org: str, obj_type: str,
qml: str) -> QgsVectorLayer:
lyr = project.mapLayersByName(obj_type)
if lyr:
return lyr[0]

lyr = QgsVectorLayer(org, obj_type, 'memory')


lyr.dataProvider().addAttributes(self.flds)
lyr.updateFields()
# QgsProject.instance().addMapLayer(lyr)
add_map_layer_to_group(lyr, search_group_name, force_create=True)
direc = os.path.dirname(__file__)
lyr.loadNamedStyle(os.path.join(direc, qml))
return lyr

def fetch_parcel_by_xy(self):
if self.clicked_x is not None and self.clicked_y is not None:
params = '&result=geom_wkt,teryt,voivodeship,county,region,commune,parcel'
url = f'https://uldk.gugik.gov.pl/?request=GetParcelByXY&xy={self.clicked_x},{self.clicked_y}{params}'
#print(url)
fetcher = FetchULDK()
if fetcher.fetch(url):
parser = ParseResponce()
parser.get_layer() # Ensure the layer is initialized
parser.parse_responce(fetcher.responce)
else:
iface.messageBar().pushMessage("Error", "Failed to fetch parcel", level=Qgis.Critical)


class PrintClickedPoint(QgsMapToolEmitPoint):
def __init__(self, canvas, searcher_tool, mode='parcel'):
super().__init__(canvas)
self.canvas = canvas
self.searcher_tool = searcher_tool
self.mode = mode

def canvasPressEvent(self, e):
point = self.toMapCoordinates(self.canvas.mouseLastXY())
self.searcher_tool.on_point_callback(point, self.mode)

############################################################################
41 changes: 41 additions & 0 deletions StyleManager/stylemanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@

from ..utils import DEFAULT_STYLE, tr, Qt

################################################################
from qgis.PyQt.QtCore import QSize
################################################################

FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'ui_stylemanager.ui'))

Expand All @@ -24,8 +28,19 @@ def __init__(self, style_mn):

# self.pushButton_add.clicked.connect(self.add_style)
# self.pushButton_delete.clicked.connect(self.delete_style)

self.pushButton_default.clicked.connect(self.set_default)
self.pushButton_activate.clicked.connect(self.change_style)

########################################################################
self.icon_size = 24

# icon_size = 16
# self.pushButton_default.setIconSize(QSize(icon_size, icon_size))
# self.pushButton_activate.setIconSize(QSize(icon_size, icon_size))

# self.adjust_icon_sizes()
########################################################################

def add_style(self):
""" add new style"""
Expand Down Expand Up @@ -69,6 +84,32 @@ def change_style(self):
return

res, msg = self.mn.activate_style(name)

########################################################################
def adjust_icon_sizes(self):
self.pushButton_default.setIconSize(QSize(self.icon_size, self.icon_size))
self.pushButton_activate.setIconSize(QSize(self.icon_size, self.icon_size))

# def set_default(self):
# """Set default qgis style"""
# res, msg = self.mn.activate_style(DEFAULT_STYLE)
# if res:
# QMessageBox.information(self, tr("Set Default Style"), tr("Default style set successfully."))
# else:
# QMessageBox.warning(self, tr("Set Default Style"), tr("Failed to set default style: %s") % msg)

# def change_style(self):
# """Change style to user selected"""
# try:
# name = self.listWidget.currentItem().text()
# except Exception:
# return
# res, msg = self.mn.activate_style(name)
# if res:
# QMessageBox.information(self, tr("Change Style"), tr("Style changed successfully."))
# else:
# QMessageBox.warning(self, tr("Change Style"), tr("Failed to change style: %s") % msg)
########################################################################

def hide(self):
"""unload dialog"""
Expand Down
14 changes: 14 additions & 0 deletions giap_dynamic_layout.ui
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,13 @@ or fill in the previous fields and indicate the parcel number e.g. 17/2</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonParcelNr">
<property name="text">
<string>Wskaż z mapy</string>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
Expand Down Expand Up @@ -247,6 +254,13 @@ for the street: Warszawa, Pasaż Ursynowski</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonAdress">
<property name="text">
<string>Wskaż z mapy</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
Expand Down
2 changes: 1 addition & 1 deletion giap_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ def show_settings_dialog(self) -> None:
self.set_dlg.radioButton_en.setChecked(True)
elif str(QSettings().value('locale/userLocale')) == "pl_PL":
self.set_dlg.radioButton_pl.setChecked(True)
self.set_dlg.spinBox_font.setValue(int(self.font_size))
self.set_dlg.spinBox_font.setValue(int(self.font_size or 5))
self.set_dlg.spinBox_button.clicked.connect(self.set_size)
self.set_dlg.restart_button.clicked.connect(self.restart_font_size)
self.set_dlg.exec_()
Expand Down
2 changes: 1 addition & 1 deletion 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