/
OsmLoadDlg.py
executable file
·336 lines (257 loc) · 12.8 KB
/
OsmLoadDlg.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# -*- coding: utf-8 -*-
"""
***************************************************************************
OsmLoadDlg.py
---------------------
Date : August 2009
Copyright : (C) 2009 by Martin Dobias
Email : wonder dot sk at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Martin Dobias'
__date__ = 'August 2009'
__copyright__ = '(C) 2009, Martin Dobias'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
# -*- coding: utf-8 -*-
"""@package OsmLoadDlg
This module provides all structures and methods necessary for OSM data loading.
Loading is done from XML file. After XML file selection and confirming the dialog three vector layers
are created in Quantum GIS. Layer for points, one for lines and one for polygons.
All these layers are created with OSM data provider.
Data provider is the one, who parses an input XML file.
OSM data loading can be canceled, in such case system returns to the same state as the one before loading.
"""
from ui_OsmLoadDlg import Ui_OsmLoadDlg
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sip import unwrapinstance
from qgis.core import QgsVectorLayer, QgsMapLayerRegistry, QgsRectangle
from sip import *
class OsmLoadDlg(QDialog, Ui_OsmLoadDlg):
"""This class provides all structures and methods necessary for OSM data loading.
Loading is done from XML file. After XML file selection and confirming the dialog three vector layers
are created in Quantum GIS. Layer for points, one for lines and one for polygons.
All these layers are created with OSM data provider.
Data provider is the one, who parses an input XML file.
OSM data loading can be canceled, in such case system returns to the same state as the one before loading.
"""
def __init__(self, plugin):
"""The constructor.
@param plugin is pointer to instance of OSM Plugin
"""
QDialog.__init__(self, plugin.iface.mainWindow())
self.setupUi(self)
self.canvas=plugin.canvas
self.dbm=plugin.dbm
self.progress = None
# we must connect action "click on browse button" with method for showing open file dialog
QObject.connect(self.browseOSMButton,SIGNAL("clicked()"),self.showOpenFileDialog)
QObject.connect(self.buttonBox,SIGNAL("accepted()"), self.onOK)
for tag in ['name','place','highway','landuse','waterway','railway','amenity','tourism','learning']:
item = QListWidgetItem(tag, self.lstTags)
item.setFlags( Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setCheckState(Qt.Checked if tag == 'name' else Qt.Unchecked)
# gui initialization
self.initGui()
def initGui(self):
"""Initializes GUI of OSM Load dialog.
"""
# load default values to combobox determining style for custom renderer
self.styles=["Small scale","Medium scale","Large scale"]
directory=QFileInfo(__file__).canonicalPath()
self.styleFiles=[directory+"/styles/small_scale.style", directory+"/styles/medium_scale.style", directory+"/styles/big_scale.style"]
self.styleCombo.addItems(self.styles)
if not self.dbm.currentKey:
self.chkReplaceData.setEnabled(False)
def showOpenFileDialog(self):
"""Function opens dialog for selecting XML file.
Only files with extension .osm can be selected.
Default directory for file selection is remembered/reload.
"""
settings=QSettings()
lastDir=settings.value("/OSM_Plugin/lastDir", QVariant(QString())).toString()
# display file open dialog and get absolute path to selected file
fileSelected=QFileDialog.getOpenFileName(self,self.tr("Choose an Open Street Map file"),lastDir,self.tr("OSM Files (*.osm)"));
# insert OSM file path into line edit control
if not fileSelected.isNull():
self.OSMFileEdit.setText(fileSelected)
# save directory
fi=QFileInfo(fileSelected)
settings.setValue("/OSM_Plugin/lastDir", QVariant(fi.path()) )
def onOK(self):
"""Function is called after clicking on OK button of OSM Load dialog.
It performs all actions necessary for OSM data loading.
It creates three QGIS vector layers for loaded data (point,line,polygon layer).
"""
self.buttonBox.setEnabled(False)
# after closing a dialog, we want to add map layers using osm provider
self.fname = self.OSMFileEdit.text()
if self.fname=='':
QMessageBox.information(self, self.tr("OSM Load"),self.tr("Please enter path to OSM data file."))
self.buttonBox.setEnabled(True)
return
osmfile = QFileInfo(self.fname)
observer = "&observer="+str(unwrapinstance(self))
basename = osmfile.baseName()
if not osmfile.exists():
QMessageBox.information(self, self.tr("OSM Load"), self.tr("Path to OSM file is invalid: %1.").arg(self.fname))
return
fLoaded=self.filesLoaded()
replacing=self.chkReplaceData.isChecked()
newDB=self.fname.toAscii().data()+".db"
curDB=self.dbm.currentKey
if basename in fLoaded and newDB<>curDB:
QMessageBox.information(self, self.tr("Error"), self.tr("Layers of OSM file \"%1\" are loaded already.").arg(self.fname))
return
if replacing:
# remove layers of current data first
QgsMapLayerRegistry.instance().removeMapLayers([self.canvas.currentLayer().id()],True)
if self.chkCustomRenderer.isChecked():
styleFile=self.styleFiles[self.styleCombo.currentIndex()]
style="&style="+styleFile
else:
style=""
# some specific tags?
tag = ""
for row in xrange(self.lstTags.count()):
item = self.lstTags.item(row)
if item.checkState() == Qt.Checked:
if len(tag) > 0: tag += "+"
tag += item.text()
if len(tag) > 0:
tag = "&tag=" + tag
# freeze map canvas until all vector layers are created
self.canvas.freeze(True)
self.loadingCanceled=False
self.setProperty("osm_stop_parsing",QVariant(0))
# add polygon layer
polygonLayer = QgsVectorLayer(self.fname+"?type=polygon"+observer + tag + style, basename+" polygons", "osm")
if self.loadingCanceled:
polygonLayer=None
return
if not polygonLayer.isValid():
QMessageBox.information(self,self.tr("Error"),self.tr("Failed to load polygon layer."))
return
if self.chkCustomRenderer.isChecked():
self.setCustomRenderer(polygonLayer)
QgsMapLayerRegistry.instance().addMapLayers([polygonLayer])
# add line layer
lineLayer = QgsVectorLayer(self.fname+"?type=line"+observer + tag + style, basename+" lines", "osm")
if self.loadingCanceled:
lineLayer=None
return
if not lineLayer.isValid():
QMessageBox.information(self,self.tr("Error"),self.tr("Failed to load line layer."))
return
if self.chkCustomRenderer.isChecked():
self.setCustomRenderer(lineLayer)
QgsMapLayerRegistry.instance().addMapLayers([lineLayer])
# add point layer
pointLayer = QgsVectorLayer(self.fname+"?type=point"+observer + tag + style, basename+" points", "osm")
if self.loadingCanceled:
pointLayer=None
return
if not pointLayer.isValid():
QMessageBox.information(self,self.tr("Error"),self.tr("Failed to load point layer."))
return
if self.chkCustomRenderer.isChecked():
self.setCustomRenderer(pointLayer)
QgsMapLayerRegistry.instance().addMapLayers([pointLayer])
# remember layers
self.polygonLayer=polygonLayer
self.lineLayer=lineLayer
self.pointLayer=pointLayer
self.canvas.freeze(False)
rect=self.canvas.extent()
if self.chkCustomRenderer.isChecked():
midX=rect.xMinimum()+(rect.xMaximum()-rect.xMinimum())/2
midY=rect.yMinimum()+(rect.yMaximum()-rect.yMinimum())/2
rX=rect.xMaximum()-midX
rY=rect.yMaximum()-midY
st=self.styles[self.styleCombo.currentIndex()]
if st=="Small scale":
rect=QgsRectangle(midX-rX/5,midY-rY/5,midX+rX/5,midY+rY/5)
elif st=="Medium scale":
rect=QgsRectangle(midX-rX/2,midY-rY/2,midX+rX/2,midY+rY/2)
self.canvas.setExtent(rect)
self.canvas.refresh()
self.accept()
def setCustomRenderer(self, layer):
"""Function provides a way how to set custom renderer.
@param layer pointer to QGIS vector layer
"""
if QObject.connect( self, SIGNAL( "setRenderer(QgsVectorLayer *)" ), layer.dataProvider(), SLOT( "setRenderer( QgsVectorLayer * )" ) ):
self.emit( SIGNAL( "setRenderer(QgsVectorLayer *)" ), layer )
QObject.disconnect( self, SIGNAL( "setRenderer(QgsVectorLayer *)" ), layer.dataProvider(), SLOT( "setRenderer( QgsVectorLayer * )" ) )
else:
QMessageBox.information(self, self.tr("OSM Load"), self.tr("Could not connect to setRenderer signal."))
def filesLoaded(self):
"""Function returns list of keys of all currently loaded vector layers.
Note that names are not absolute and not unique.
@return list of keys of all currently loaded vector layers
"""
mapLayers=QgsMapLayerRegistry.instance().mapLayers()
fLoaded=[]
for ix in mapLayers.keys():
fileName=QString(ix)
pos=ix.lastIndexOf("_")
fileName=fileName.left(pos)
if fileName not in fLoaded:
fLoaded.append(fileName)
return fLoaded
def cancelLoading(self):
"""Function is called when progress dialog is canceled
It's purpose is to tell OSM provider to stop XML file parsing.
"""
self.setProperty("osm_stop_parsing",QVariant(1))
self.loadingCanceled=True
def event(self, e):
"""Function is used for OSM provider <-> OSM Plugin communication.
"""
if e.type() == QEvent.DynamicPropertyChange:
if e.propertyName() == "osm_status":
# we're starting new part
if not self.progress:
self.progress = QProgressDialog(self)
self.progress.setAutoClose(False)
self.progress.setModal(True)
QObject.connect(self.progress,SIGNAL("canceled()"),self.cancelLoading)
self.progress.show()
status = self.property("osm_status").toString()
self.progress.setLabelText(status)
self.progress.setValue(0)
if e.propertyName() == "osm_max":
if not self.loadingCanceled:
# we've got new max. value
osm_max = self.property("osm_max").toInt()[0]
self.progress.setMaximum(osm_max)
elif e.propertyName() == "osm_value":
if not self.loadingCanceled:
# update in progressbar
osm_val = self.property("osm_value").toInt()[0]
self.progress.setValue(osm_val)
elif e.propertyName() == "osm_done":
if not self.loadingCanceled:
# we're done
QObject.disconnect(self.progress,SIGNAL("canceled()"),self.cancelLoading)
self.progress.close()
self.progress = None
elif e.propertyName() == "osm_failure":
if not self.loadingCanceled:
self.loadingCanceled=True
QObject.disconnect(self.progress,SIGNAL("canceled()"),self.cancelLoading)
self.progress.close()
self.progress = None
QMessageBox.information(self,self.tr("Error"),self.tr("Failed to load layers: %1")
.arg(self.property("osm_failure").toString()))
self.buttonBox.setEnabled(True)
qApp.processEvents()
return QDialog.event(self,e)