forked from NationalSecurityAgency/qgis-latlontools-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeom2field.py
295 lines (268 loc) · 12.2 KB
/
geom2field.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
import os
from qgis.PyQt.QtCore import QVariant, QCoreApplication, QUrl
from qgis.PyQt.QtGui import QIcon
from qgis.core import QgsFields, QgsField, QgsFeature, QgsCoordinateTransform, QgsProject
from qgis.core import (
QgsProcessing,
QgsProcessingException,
QgsProcessingAlgorithm,
QgsProcessingParameterEnum,
QgsProcessingParameterString,
QgsProcessingParameterNumber,
QgsProcessingParameterCrs,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink)
from . import mgrs
from .util import epsg4326, convertDD2DMS, formatDmsString
from .utm import latLon2UtmString
from . import olc
def tr(string):
return QCoreApplication.translate('Processing', string)
class Geom2FieldAlgorithm(QgsProcessingAlgorithm):
"""
Algorithm to convert a point layer to a Plus codes field.
"""
# Constants used to refer to parameters and outputs. They will be
# used when calling the algorithm from another algorithm, or when
# calling from the QGIS console.
PrmInputLayer = 'InputLayer'
PrmOutputFormat = 'OutputFormat'
PrmYFieldName = 'YFieldName'
PrmXFieldName = 'XFieldName'
PrmCoordinateOrder = 'CoordinateOrder'
PrmCoordinateDelimiter = 'CoordinateDelimiter'
PrmOutputCRSType = 'OutputCRSType'
PrmCustomCRS = 'CustomCRS'
PrmWgs84NumberFormat = 'Wgs84NumberFormat'
PrmCoordinatePrecision = 'CoordinatePrecision'
PrmDMSSecondPrecision = 'DMSSecondPrecision'
PrmPlusCodesLength = 'PlusCodesLength'
PrmOutputLayer = 'OutputLayer'
def initAlgorithm(self, config):
self.addParameter(
QgsProcessingParameterFeatureSource(
self.PrmInputLayer,
tr('Input point vector layer'),
[QgsProcessing.TypeVectorPoint])
)
self.addParameter(
QgsProcessingParameterEnum(
self.PrmOutputFormat,
tr('Output format'),
options=[
tr('Coordinates in 2 fields'),
tr('Coordinates in 1 field'),
tr('GeoJSON'), tr('WKT'), tr('MGRS'),
tr('Plus Codes'), tr('Standard UTM')],
defaultValue=0,
optional=True)
)
self.addParameter(
QgsProcessingParameterString(
self.PrmXFieldName,
tr('Longitude (X) field name'),
defaultValue='x',
optional=True)
)
self.addParameter(
QgsProcessingParameterString(
self.PrmYFieldName,
tr('Latitude (Y) & all other formats field name'),
defaultValue='y',
optional=True)
)
self.addParameter(
QgsProcessingParameterEnum(
self.PrmCoordinateOrder,
tr('Coordinate order when using 1 field'),
options=[tr('Lat,Lon (Y,X) - Google map order'), tr('Lon,Lat (X,Y) order')],
defaultValue=0,
optional=True)
)
self.addParameter(
QgsProcessingParameterString(
self.PrmCoordinateDelimiter,
tr('Delimiter between coordinates when using 1 field'),
defaultValue=',',
optional=True)
)
self.addParameter(
QgsProcessingParameterEnum(
self.PrmOutputCRSType,
tr('Output CRS of coordinates added to a field'),
options=[tr('WGS 84'), tr('Layer CRS'), tr('Project CRS'), tr('Custom CRS')],
defaultValue=0,
optional=True)
)
self.addParameter(
QgsProcessingParameterCrs(
self.PrmCustomCRS,
tr('Custom CRS for coordinates added to a field'),
'EPSG:4326',
optional=True)
)
self.addParameter(
QgsProcessingParameterEnum(
self.PrmWgs84NumberFormat,
tr('Select Decimal or DMS degress for WGS 84 numbers'),
options=[tr('Decimal degrees'), tr('DMS'), tr('DDMMSS')],
defaultValue=0,
optional=True)
)
self.addParameter(
QgsProcessingParameterNumber(
self.PrmCoordinatePrecision,
tr('Decimal number precision'),
type=QgsProcessingParameterNumber.Integer,
defaultValue=8,
optional=True,
minValue=0)
)
self.addParameter(
QgsProcessingParameterNumber(
self.PrmDMSSecondPrecision,
tr('DMS second / UTM precision'),
type=QgsProcessingParameterNumber.Integer,
defaultValue=0,
optional=True,
minValue=0)
)
self.addParameter(
QgsProcessingParameterNumber(
self.PrmPlusCodesLength,
tr('Plus Codes length'),
type=QgsProcessingParameterNumber.Integer,
defaultValue=11,
optional=True,
minValue=10,
maxValue=20)
)
self.addParameter(
QgsProcessingParameterFeatureSink(
self.PrmOutputLayer,
tr('Output layer'))
)
def processAlgorithm(self, parameters, context, feedback):
source = self.parameterAsSource(parameters, self.PrmInputLayer, context)
outputFormat = self.parameterAsInt(parameters, self.PrmOutputFormat, context)
field1Name = self.parameterAsString(parameters, self.PrmYFieldName, context).strip()
field2Name = self.parameterAsString(parameters, self.PrmXFieldName, context).strip()
coordOrder = self.parameterAsInt(parameters, self.PrmCoordinateOrder, context)
delimiter = self.parameterAsString(parameters, self.PrmCoordinateDelimiter, context)
crsType = self.parameterAsInt(parameters, self.PrmOutputCRSType, context)
crsOther = self.parameterAsCrs(parameters, self.PrmCustomCRS, context)
wgs84Format = self.parameterAsInt(parameters, self.PrmWgs84NumberFormat, context)
decimalPrecision = self.parameterAsInt(parameters, self.PrmCoordinatePrecision, context)
dmsPrecision = self.parameterAsInt(parameters, self.PrmDMSSecondPrecision, context)
plusCodesLength = self.parameterAsInt(parameters, self.PrmPlusCodesLength, context)
layerCRS = source.sourceCrs()
# For the first condition, the user has either EPSG:4326 selected or
# or have chosen GeoJSON or WKT which will be 4326 as well
if crsType == 0 or outputFormat >= 2: # Forced WGS 84
outCRS = epsg4326
elif crsType == 1: # Layer CRS
outCRS = layerCRS
elif crsType == 2: # Project CRS
outCRS = QgsProject.instance().crs()
else:
outCRS = crsOther
fieldsout = QgsFields(source.fields())
if fieldsout.append(QgsField(field1Name, QVariant.String)) is False:
msg = "Field names must be unique. There is already a field named '{}'".format(field1Name)
feedback.reportError(msg)
raise QgsProcessingException(msg)
if outputFormat == 0: # Two fields for coordinates
if fieldsout.append(QgsField(field2Name, QVariant.String)) is False:
msg = "Field names must be unique. There is already a field named '{}'".format(field2Name)
feedback.reportError(msg)
raise QgsProcessingException(msg)
(sink, dest_id) = self.parameterAsSink(
parameters, self.PrmOutputLayer,
context, fieldsout, source.wkbType(), layerCRS)
if layerCRS != outCRS:
transform = QgsCoordinateTransform(layerCRS, outCRS, QgsProject.instance())
total = 100.0 / source.featureCount() if source.featureCount() else 0
iterator = source.getFeatures()
for cnt, feature in enumerate(iterator):
if feedback.isCanceled():
break
pt = feature.geometry().asPoint()
if layerCRS != outCRS:
pt = transform.transform(pt)
try:
if outputFormat == 0: # Two fields for coordinates
if outCRS == epsg4326:
if wgs84Format == 0: # Decimal Degrees
msg = '{:.{prec}f}'.format(pt.y(), prec=decimalPrecision)
msg2 = '{:.{prec}f}'.format(pt.x(), prec=decimalPrecision)
elif wgs84Format == 1: # DMS
msg = convertDD2DMS(pt.y(), True, True, dmsPrecision)
msg2 = convertDD2DMS(pt.x(), False, True, dmsPrecision)
else: # DDMMSS
msg = convertDD2DMS(pt.y(), True, False, dmsPrecision)
msg2 = convertDD2DMS(pt.x(), False, False, dmsPrecision)
else:
msg = '{:.{prec}f}'.format(pt.y(), prec=decimalPrecision)
msg2 = '{:.{prec}f}'.format(pt.x(), prec=decimalPrecision)
elif outputFormat == 1: # One field for coordinate
if outCRS == epsg4326:
if wgs84Format == 0: # Decimal Degrees
if coordOrder == 0:
msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt.y(), delimiter, pt.x(), prec=decimalPrecision)
else:
msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt.x(), delimiter, pt.y(), prec=decimalPrecision)
elif wgs84Format == 1: # DMS
msg = formatDmsString(pt.y(), pt.x(), True, dmsPrecision, coordOrder, delimiter)
else: # DDMMSS
msg = formatDmsString(pt.y(), pt.x(), False, dmsPrecision, coordOrder, delimiter)
else:
if coordOrder == 0:
msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt.y(), delimiter, pt.x(), prec=decimalPrecision)
else:
msg = '{:.{prec}f}{}{:.{prec}f}'.format(pt.x(), delimiter, pt.y(), prec=decimalPrecision)
elif outputFormat == 2: # GeoJSON
msg = '{{"type": "Point","coordinates": [{:.{prec}f},{:.{prec}f}]}}'.format(pt.x(), pt.y(), prec=decimalPrecision)
elif outputFormat == 3: # WKT
msg = 'POINT({:.{prec}f} {:.{prec}f})'.format(pt.x(), pt.y(), prec=decimalPrecision)
elif outputFormat == 4: # MGRS
msg = mgrs.toMgrs(pt.y(), pt.x(), 5)
elif outputFormat == 5: # Plus codes
msg = olc.encode(pt.y(), pt.x(), plusCodesLength)
else: # WGS 84 UTM
msg = latLon2UtmString(pt.y(), pt.x(), dmsPrecision)
except Exception:
msg = ''
f = QgsFeature()
f.setGeometry(feature.geometry())
if outputFormat == 0: # Two fields for coordinates
f.setAttributes(feature.attributes() + [msg, msg2])
else:
f.setAttributes(feature.attributes() + [msg])
sink.addFeature(f)
if cnt % 100 == 0:
feedback.setProgress(int(cnt * total))
return {self.PrmOutputLayer: dest_id}
def name(self):
return 'geom2field'
def icon(self):
return QIcon(os.path.dirname(__file__) + '/images/geom2field.png')
def displayName(self):
return 'Point layer to fields'
def group(self):
return 'Vector conversion'
def groupId(self):
return 'vectorconversion'
def helpUrl(self):
file = os.path.dirname(__file__) + '/index.html'
if not os.path.exists(file):
return ''
return QUrl.fromLocalFile(file).toString(QUrl.FullyEncoded)
def shortHelpString(self):
file = os.path.dirname(__file__) + '/doc/geom2fields.help'
if not os.path.exists(file):
return ''
with open(file) as helpf:
help = helpf.read()
return help
def createInstance(self):
return Geom2FieldAlgorithm()