forked from NationalSecurityAgency/qgis-latlontools-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mgrstogeom.py
86 lines (69 loc) · 3.09 KB
/
mgrstogeom.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
import os
import re
from PyQt4.QtGui import QDialog
from PyQt4.uic import loadUiType
from PyQt4.QtCore import QVariant
from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsPoint, QgsMapLayerRegistry
from qgis.gui import QgsMapLayerProxyModel, QgsMessageBar
#import traceback
import mgrs
FORM_CLASS, _ = loadUiType(os.path.join(
os.path.dirname(__file__), 'ui/mgrstolayer.ui'))
class MGRStoLayerWidget(QDialog, FORM_CLASS):
'''Convert an MGRS field to a point geometry layer.'''
def __init__(self, iface, parent):
super(MGRStoLayerWidget, self).__init__(parent)
self.setupUi(self)
self.iface = iface
self.mMapLayerComboBox.setFilters(QgsMapLayerProxyModel.VectorLayer | QgsMapLayerProxyModel.NoGeometry)
self.mMapLayerComboBox.layerChanged.connect(self.layerChanged)
def accept(self):
layer = self.mMapLayerComboBox.currentLayer()
if not layer:
self.iface.messageBar().pushMessage("", "No Valid Layer to Process", level=QgsMessageBar.WARNING, duration=4)
return
layer_name = self.nameLineEdit.text()
selectedField = self.mFieldComboBox.currentField()
fieldIndex = layer.fieldNameIndex(selectedField)
if fieldIndex == -1:
self.iface.messageBar().pushMessage("", "Invalid MGRS Field", level=QgsMessageBar.WARNING, duration=4)
return
fields = layer.pendingFields()
# Check to see if the field is of the right type
f = fields.at(fieldIndex)
if f.type() != QVariant.String:
self.iface.messageBar().pushMessage("", "Selected MGRS Field is not a valid data type", level=QgsMessageBar.WARNING, duration=4)
return
pointLayer = QgsVectorLayer("Point?crs=epsg:4326", layer_name, "memory")
ppoint = pointLayer.dataProvider()
ppoint.addAttributes(fields)
pointLayer.updateFields()
iter = layer.getFeatures()
num_features = 0
num_bad = 0
for feature in iter:
num_features += 1
m = feature[fieldIndex]
try:
m = re.sub(r'\s+', '', unicode(m)) # Remove all white space
lat, lon = mgrs.toWgs(m)
except:
#traceback.print_exc()
num_bad += 1
continue
f = QgsFeature()
f.setGeometry(QgsGeometry.fromPoint(QgsPoint(lon,lat)))
f.setAttributes(feature.attributes())
ppoint.addFeatures([f])
pointLayer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayer(pointLayer)
if num_bad != 0:
self.iface.messageBar().pushMessage("", "{} out of {} features failed".format(num_bad, num_features), level=QgsMessageBar.WARNING, duration=4)
self.close()
def layerChanged(self):
if not self.isVisible():
return
layer = self.mMapLayerComboBox.currentLayer()
self.mFieldComboBox.setLayer(layer)
def showEvent(self, event):
self.layerChanged()