-
Notifications
You must be signed in to change notification settings - Fork 0
/
qgis_wkt_extraction.py
43 lines (34 loc) · 1.38 KB
/
qgis_wkt_extraction.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
"""A collection of functions to extract WKT from selected features."""
from qgis.core import (
Qgis,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsProject,
)
from qgis.utils import iface
def get_wkt_of_selected_feature(precision=4):
"""Returns the WKT of the first selected polygon in WGS84."""
# grab the active layer and the list of selected features in this layer
active_layer = iface.activeLayer()
selected_features = active_layer.selectedFeatures()
# if none are selected, show a message and return
if len(selected_features) == 0:
iface.messageBar().pushMessage(
"Error",
"No features selected",
level=Qgis.Critical,
duration=3,
)
return
# if there are selected features, grab the first and extract the geometry
selected_feature = selected_features[0]
geometry = selected_feature.geometry()
# reproject to WGS84 if active layer has a different CRS
source_crs = active_layer.crs()
if source_crs.authid() != "EPSG:4326":
# the QgsCoordinateTransform needs the project for some reason
project = QgsProject.instance()
target_crs = QgsCoordinateReferenceSystem("EPSG:4326")
transform = QgsCoordinateTransform(source_crs, target_crs, project)
geometry.transform(transform)
return geometry.asWkt(precision=precision)