def affine(self): warn = QgsMessageViewer() layer_name = self.ui.comboBoxLayer.currentText() vlayer = self.project.mapLayers().get(layer_name) if vlayer is None: warn.setMessageAsPlainText("Select a layer to transform") warn.showMessage() return if not vlayer.isEditable(): warn.setMessageAsPlainText("Layer not in edit mode") warn.showMessage() return if self.ui.radioButtonWholeLayer.isChecked(): vlayer.selectAll() if vlayer.geometryType() == QgsWkbTypes.PolygonGeometry: start = 1 else: start = 0 v = self.affine_namespace for fid in vlayer.selectedFeatureIds(): feature = vlayer.getFeature(fid) geometry = feature.geometry() for i in itertools.count(start=start): vertex = geometry.vertexAt(i) if vertex == QgsPoint(0, 0): break # matrix form: x' = A x + b # x' = a x + b y + tx # y' = c x + d y + ty newx = v.a * vertex.x() + v.b * vertex.y() + v.tx newy = v.c * vertex.x() + v.d * vertex.y() + v.ty vlayer.moveVertex(newx, newy, fid, i) if self.ui.checkBoxZoomToLayer.isChecked(): self.iface.mapCanvas().zoomToSelected()
def invert(self): # matrix form: x' = A x + b # --> x = A^-1 x' - A^-1 b # A^-1 = [d -b; -c a] / det A # only valid if det A = a d - b c != 0 v = self.affine_namespace det = v.a * v.d - v.b * v.c if det == 0: warn = QgsMessageViewer() warn.setMessageAsPlainText("Transformation is not invertable") warn.showMessage() return v.a, v.b, v.c, v.d = v.d / det, -v.b / det, -v.c / det, v.a / det v.tx, v.ty = -v.a * v.tx - v.b * v.ty, -v.c * v.tx - v.d * v.ty
def accept(self): if self.mode == self.ASK_FOR_INPUT_MODE: # create the input layer (if not already done) and # update available options self.reloadInputLayer() # sanity checks if self.inLayer is None: QMessageBox.information( self, self.tr("Import to database"), self.tr("Input layer missing or not valid")) return if self.cboTable.currentText() == "": QMessageBox.information(self, self.tr("Import to database"), self.tr("Output table name is required")) return if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): try: sourceSrid = self.editSourceSrid.text() except ValueError: QMessageBox.information( self, self.tr("Import to database"), self.tr("Invalid source srid: must be an integer")) return if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): try: targetSrid = self.editTargetSrid.text() except ValueError: QMessageBox.information( self, self.tr("Import to database"), self.tr("Invalid target srid: must be an integer")) return # override cursor QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # store current input layer crs and encoding, so I can restore it prevInCrs = self.inLayer.crs() prevInEncoding = self.inLayer.dataProvider().encoding() try: schema = self.outUri.schema() if not self.cboSchema.isEnabled( ) else self.cboSchema.currentText() table = self.cboTable.currentText() # get pk and geom field names from the source layer or use the # ones defined by the user srcUri = QgsDataSourceURI(self.inLayer.source()) pk = srcUri.keyColumn() if not self.chkPrimaryKey.isChecked( ) else self.editPrimaryKey.text() if not pk: pk = self.default_pk if self.inLayer.hasGeometryType() and self.chkGeomColumn.isEnabled( ): geom = srcUri.geometryColumn( ) if not self.chkGeomColumn.isChecked( ) else self.editGeomColumn.text() if not geom: geom = self.default_geom else: geom = None options = {} if self.chkLowercaseFieldNames.isEnabled( ) and self.chkLowercaseFieldNames.isChecked(): pk = pk.lower() if geom: geom = geom.lower() options['lowercaseFieldNames'] = True # get output params, update output URI self.outUri.setDataSource(schema, table, geom, "", pk) typeName = self.db.dbplugin().typeName() providerName = self.db.dbplugin().providerName() if typeName == 'gpkg': uri = self.outUri.database() options['update'] = True options['driverName'] = 'GPKG' options['layerName'] = table else: uri = self.outUri.uri(False) if self.chkDropTable.isChecked(): options['overwrite'] = True if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked( ): options['forceSinglePartGeometryType'] = True outCrs = None if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked( ): targetSrid = int(self.editTargetSrid.text()) outCrs = QgsCoordinateReferenceSystem(targetSrid) # update input layer crs and encoding if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked( ): sourceSrid = int(self.editSourceSrid.text()) inCrs = QgsCoordinateReferenceSystem(sourceSrid) self.inLayer.setCrs(inCrs) if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked(): enc = self.cboEncoding.currentText() self.inLayer.setProviderEncoding(enc) onlySelected = self.chkSelectedFeatures.isChecked() # do the import! ret, errMsg = QgsVectorLayerImport.importLayer( self.inLayer, uri, providerName, outCrs, onlySelected, False, options) except Exception as e: ret = -1 errMsg = unicode(e) finally: # restore input layer crs and encoding self.inLayer.setCrs(prevInCrs) self.inLayer.setProviderEncoding(prevInEncoding) # restore cursor QApplication.restoreOverrideCursor() if ret != 0: output = QgsMessageViewer() output.setTitle(self.tr("Import to database")) output.setMessageAsPlainText( self.tr("Error %d\n%s") % (ret, errMsg)) output.showMessage() return # create spatial index if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked( ): self.db.connector.createSpatialIndex((schema, table), geom) self.db.connection().reconnect() self.db.refresh() QMessageBox.information(self, self.tr("Import to database"), self.tr("Import was successful.")) return QDialog.accept(self)
def accept(self): if self.mode == self.ASK_FOR_INPUT_MODE: # create the input layer (if not already done) and # update available options self.reloadInputLayer() # sanity checks if self.inLayer is None: QMessageBox.information(self, self.tr("Import to database"), self.tr("Input layer missing or not valid")) return if self.cboTable.currentText() == "": QMessageBox.information(self, self.tr("Import to database"), self.tr("Output table name is required")) return if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): try: sourceSrid = self.editSourceSrid.text() except ValueError: QMessageBox.information(self, self.tr("Import to database"), self.tr("Invalid source srid: must be an integer")) return if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): try: targetSrid = self.editTargetSrid.text() except ValueError: QMessageBox.information(self, self.tr("Import to database"), self.tr("Invalid target srid: must be an integer")) return # override cursor QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # store current input layer crs and encoding, so I can restore it prevInCrs = self.inLayer.crs() prevInEncoding = self.inLayer.dataProvider().encoding() try: schema = self.outUri.schema() if not self.cboSchema.isEnabled() else self.cboSchema.currentText() table = self.cboTable.currentText() # get pk and geom field names from the source layer or use the # ones defined by the user srcUri = QgsDataSourceUri(self.inLayer.source()) pk = srcUri.keyColumn() if not self.chkPrimaryKey.isChecked() else self.editPrimaryKey.text() if not pk: pk = self.default_pk if self.inLayer.hasGeometryType() and self.chkGeomColumn.isEnabled(): geom = srcUri.geometryColumn() if not self.chkGeomColumn.isChecked() else self.editGeomColumn.text() if not geom: geom = self.default_geom else: geom = None options = {} if self.chkLowercaseFieldNames.isEnabled() and self.chkLowercaseFieldNames.isChecked(): pk = pk.lower() if geom: geom = geom.lower() options['lowercaseFieldNames'] = True # get output params, update output URI self.outUri.setDataSource(schema, table, geom, "", pk) uri = self.outUri.uri(False) providerName = self.db.dbplugin().providerName() if self.chkDropTable.isChecked(): options['overwrite'] = True if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked(): options['forceSinglePartGeometryType'] = True outCrs = QgsCoordinateReferenceSystem() if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): targetSrid = int(self.editTargetSrid.text()) outCrs = QgsCoordinateReferenceSystem(targetSrid) # update input layer crs and encoding if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): sourceSrid = int(self.editSourceSrid.text()) inCrs = QgsCoordinateReferenceSystem(sourceSrid) self.inLayer.setCrs(inCrs) if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked(): enc = self.cboEncoding.currentText() self.inLayer.setProviderEncoding(enc) onlySelected = self.chkSelectedFeatures.isChecked() # do the import! ret, errMsg = QgsVectorLayerImport.importLayer(self.inLayer, uri, providerName, outCrs, onlySelected, False, options) except Exception as e: ret = -1 errMsg = str(e) finally: # restore input layer crs and encoding self.inLayer.setCrs(prevInCrs) self.inLayer.setProviderEncoding(prevInEncoding) # restore cursor QApplication.restoreOverrideCursor() if ret != 0: output = QgsMessageViewer() output.setTitle(self.tr("Import to database")) output.setMessageAsPlainText(self.tr("Error %d\n%s") % (ret, errMsg)) output.showMessage() return # create spatial index if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked(): self.db.connector.createSpatialIndex((schema, table), geom) QMessageBox.information(self, self.tr("Import to database"), self.tr("Import was successful.")) return QDialog.accept(self)
def accept(self): if self.mode == self.ASK_FOR_INPUT_MODE: # create the input layer (if not already done) and # update available options self.reloadInputLayer() # sanity checks if self.inLayer is None: QMessageBox.critical(self, self.tr("Import to Database"), self.tr("Input layer missing or not valid.")) return if self.cboTable.currentText() == "": QMessageBox.critical(self, self.tr("Import to Database"), self.tr("Output table name is required.")) return if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): if not self.widgetSourceSrid.crs().isValid(): QMessageBox.critical(self, self.tr("Import to Database"), self.tr("Invalid source srid: must be a valid crs.")) return if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): if not self.widgetTargetSrid.crs().isValid(): QMessageBox.critical(self, self.tr("Import to Database"), self.tr("Invalid target srid: must be a valid crs.")) return with OverrideCursor(Qt.WaitCursor): # store current input layer crs and encoding, so I can restore it prevInCrs = self.inLayer.crs() prevInEncoding = self.inLayer.dataProvider().encoding() try: schema = self.outUri.schema() if not self.cboSchema.isEnabled() else self.cboSchema.currentText() table = self.cboTable.currentText() # get pk and geom field names from the source layer or use the # ones defined by the user srcUri = QgsDataSourceUri(self.inLayer.source()) pk = srcUri.keyColumn() if not self.chkPrimaryKey.isChecked() else self.editPrimaryKey.text() if not pk: pk = self.default_pk if self.inLayer.isSpatial() and self.chkGeomColumn.isEnabled(): geom = srcUri.geometryColumn() if not self.chkGeomColumn.isChecked() else self.editGeomColumn.text() if not geom: geom = self.default_geom else: geom = None options = {} if self.chkLowercaseFieldNames.isEnabled() and self.chkLowercaseFieldNames.isChecked(): pk = pk.lower() if geom: geom = geom.lower() options['lowercaseFieldNames'] = True # get output params, update output URI self.outUri.setDataSource(schema, table, geom, "", pk) typeName = self.db.dbplugin().typeName() providerName = self.db.dbplugin().providerName() if typeName == 'gpkg': uri = self.outUri.database() options['update'] = True options['driverName'] = 'GPKG' options['layerName'] = table else: uri = self.outUri.uri(False) if self.chkDropTable.isChecked(): options['overwrite'] = True if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked(): options['forceSinglePartGeometryType'] = True outCrs = QgsCoordinateReferenceSystem() if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): outCrs = self.widgetTargetSrid.crs() # update input layer crs and encoding if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): inCrs = self.widgetSourceSrid.crs() self.inLayer.setCrs(inCrs) if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked(): enc = self.cboEncoding.currentText() self.inLayer.setProviderEncoding(enc) onlySelected = self.chkSelectedFeatures.isChecked() # do the import! ret, errMsg = QgsVectorLayerExporter.exportLayer(self.inLayer, uri, providerName, outCrs, onlySelected, options) except Exception as e: ret = -1 errMsg = str(e) finally: # restore input layer crs and encoding self.inLayer.setCrs(prevInCrs) self.inLayer.setProviderEncoding(prevInEncoding) if ret != 0: output = QgsMessageViewer() output.setTitle(self.tr("Import to Database")) output.setMessageAsPlainText(self.tr("Error {0}\n{1}").format(ret, errMsg)) output.showMessage() return # create spatial index if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked(): self.db.connector.createSpatialIndex((schema, table), geom) # add comment on table supportCom = self.db.supportsComment() if self.chkCom.isEnabled() and self.chkCom.isChecked() and supportCom: # using connector executing COMMENT ON TABLE query (with editCome.text() value) com = self.editCom.text() self.db.connector.commentTable(schema, table, com) self.db.connection().reconnect() self.db.refresh() QMessageBox.information(self, self.tr("Import to Database"), self.tr("Import was successful.")) return QDialog.accept(self)
class FeatureOfInterestDefinerConfigurationWidget(StandardModuleConfigurationWidget): """A widget to configure the FeatureOfInterestDefiner Module.""" def __init__(self, module, controller, parent=None): StandardModuleConfigurationWidget.__init__(self, module, controller, parent) self.foi_type = module.name #self.module = module self.setObjectName("FeatureOfInterestDefinerWidget") self.parent_widget = module # FIXME these modules don't exist self.path_png_icon = vistrails.packages.eo4vistrails.geoinf.visual.__path__[0] self.path_bkgimg = vistrails.packages.eo4vistrails.geoinf.visual.__path__[0] self.create_config_window() def create_config_window(self): """TO DO - add docstring""" self.setWindowTitle(self.foi_type) self.setMinimumSize(800, 850) self.center() self.mainLayout = QtGui.QVBoxLayout() self.setLayout(self.mainLayout) #set up Group Box for organising CRS of FOI self.crsGroupBox = QtGui.QGroupBox("Define Projection or Coordinate Reference System") self.crsLayout = QtGui.QHBoxLayout() self.crsProj4Label = QtGui.QLabel('SRS Proj4: ') self.crsTextAsProj4 = QtGui.QLineEdit('4326') self.crsChooseButton = QtGui.QPushButton('&Choose SRS') self.crsChooseButton.setAutoDefault(False) self.crsChooseButton.setToolTip('Choose a Spatial Reference System or Projection') self.crsLayout.addWidget(self.crsProj4Label) self.crsLayout.addWidget(self.crsTextAsProj4) self.crsLayout.addWidget(self.crsChooseButton) self.crsGroupBox.setLayout(self.crsLayout) #set up Group Box for getting coords of Bounding Box self.bbGroupBox = QtGui.QGroupBox("Define Area of Interest via a Bounding Box in units of SRS") self.bbLayout = QtGui.QHBoxLayout() self.bbMinXLabel = QtGui.QLabel('MinX/Left: ') self.bbMinYLabel = QtGui.QLabel('MinY/Bottom: ') self.bbMaxXLabel = QtGui.QLabel('MaxX/Right: ') self.bbMaxYLabel = QtGui.QLabel('MaxY/Top: ') self.bbMinXText = QtGui.QLineEdit('15') self.bbMinYText = QtGui.QLineEdit('-35') self.bbMaxXText = QtGui.QLineEdit('35') self.bbMaxYText = QtGui.QLineEdit('-20') self.bbToMapButton = QtGui.QPushButton('&To Map') self.bbToMapButton.setAutoDefault(False) self.bbToMapButton.setToolTip('Show Bounding Box on Map') self.bbLayout.addWidget(self.bbMinXLabel) self.bbLayout.addWidget(self.bbMinXText) self.bbLayout.addWidget(self.bbMinYLabel) self.bbLayout.addWidget(self.bbMinYText) self.bbLayout.addWidget(self.bbMaxXLabel) self.bbLayout.addWidget(self.bbMaxXText) self.bbLayout.addWidget(self.bbMaxYLabel) self.bbLayout.addWidget(self.bbMaxYText) self.bbLayout.addWidget(self.bbToMapButton) self.bbGroupBox.setLayout(self.bbLayout) #set up Group Box for getting text representation of a geometry self.asTxtGroupBox = QtGui.QGroupBox("Define Area of Interest via a WKT string in units of SRS") self.asTxtLayout = QtGui.QVBoxLayout() self.asTxtLabel = QtGui.QLabel('WKT String: ') self.asTxtText = QtGui.QTextEdit('') self.asTxtToMapButton = QtGui.QPushButton('&To Map') self.asTxtToMapButton.setAutoDefault(False) self.asTxtToMapButton.setToolTip('Show Bounding Box on Map') self.asTxtLayout.addWidget(self.asTxtLabel) self.asTxtLayout.addWidget(self.asTxtText) self.asTxtLayout.addWidget(self.asTxtToMapButton) self.asTxtGroupBox.setLayout(self.asTxtLayout) #set up Group Box for Map self.MapGroupBox = QtGui.QGroupBox("Map Viewer") self.MapLayout = QtGui.QHBoxLayout() #sz = QtCore.QSize(200, 300) #self.MapLayout.setGeometry(QtCore.QRect(300, 700, 780, 680)) self.MapGroupBox.setLayout(self.MapLayout) ## create canvas self.canvas = QgsMapCanvas() self.canvas.setCanvasColor(QtGui.QColor(200, 200, 255)) #self.mainLayout.addWidget(self.canvas) # icons actionAddLayer = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \ "/mActionAddLayer.png"), "Add Layer", self) actionZoomIn = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \ "/mActionZoomIn.png"), "Zoom In", self) actionZoomOut = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \ "/mActionZoomOut.png"), "Zoom Out", self) actionPan = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \ "/mActionPan.png"), "Pan", self) actionIdentify = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \ "/mActionIdentify.png"), "Feature Information", self) # create toolbar self.toolbar = QtGui.QToolBar() # "Canvas actions" self.toolbar.addAction(actionAddLayer) self.toolbar.addAction(actionZoomIn) self.toolbar.addAction(actionZoomOut) self.toolbar.addAction(actionPan) self.toolbar.addAction(actionIdentify) # create layer explorer pane self.explorer = QtGui.QDockWidget("Layers") self.explorer.resize(60, 100) #~self.explorerListWidget = QtGui.QListWidget() #~self.explorerListWidget.setObjectName("listWidget") #~self.explorer.setWidget(self.explorerListWidget) # create map tools self.toolPan = QgsMapToolPan(self.canvas,) self.toolPan.setAction(actionPan) self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false == in self.toolZoomIn.setAction(actionZoomIn) self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true == out self.toolZoomOut.setAction(actionZoomOut) self.toolAOI = QgsMapTool(self.canvas) self.toolIdentify = GetFeatureInfoTool(self.canvas, self.gotFeatureForIdentification) self.toolIdentify.setAction(actionIdentify) # layerList explorer self.GroupBoxLyrExplorer = QtGui.QGroupBox("") self.vboxLyrExplorer = QtGui.QVBoxLayout() self.GroupBoxLyrExplorer.setLayout(self.vboxLyrExplorer) self.MapLayout.addWidget(self.GroupBoxLyrExplorer) self.label = QtGui.QLabel("") self.vboxLyrExplorer.addWidget(self.label) self.vboxLyrExplorer.addWidget(self.explorer) # toolbar and canvas layout self.GroupBoxToolBarMapCanvas = QtGui.QGroupBox("") self.vboxToolBarMapCanvas = QtGui.QVBoxLayout() self.vboxToolBarMapCanvas.setGeometry(QtCore.QRect(300, 700, 780, 680)) self.GroupBoxToolBarMapCanvas.setLayout(self.vboxToolBarMapCanvas) self.MapLayout.addWidget(self.GroupBoxToolBarMapCanvas) self.vboxToolBarMapCanvas.addWidget(self.toolbar) self.vboxToolBarMapCanvas.addWidget(self.canvas) #global list to hold inputlayers list -> accessible for toggleLayer self.mylist = [] #finalise/cancel buttons self.finishGroupBox = QtGui.QGroupBox("Finish") self.buttonLayout = QtGui.QHBoxLayout() self.finishGroupBox.setLayout(self.buttonLayout) self.buttonLayout.setGeometry(QtCore.QRect(300, 500, 780, 680)) self.buttonLayout.setMargin(5) self.cancelButton = QtGui.QPushButton('&Cancel', self) self.cancelButton.setAutoDefault(False) self.cancelButton.setShortcut('Esc') self.buttonLayout.addStretch(1) # force buttons to the right self.buttonLayout.addWidget(self.cancelButton) self.okButton = QtGui.QPushButton('&OK', self) self.okButton.setAutoDefault(False) self.buttonLayout.addWidget(self.okButton) self.connect(self.okButton, QtCore.SIGNAL('clicked(bool)'), self.okTriggered) self.connect(self.cancelButton, QtCore.SIGNAL('clicked(bool)'), self.close) self.mainLayout.addWidget(self.crsGroupBox) self.mainLayout.addWidget(self.bbGroupBox) self.mainLayout.addWidget(self.asTxtGroupBox) self.mainLayout.addWidget(self.MapGroupBox) self.mainLayout.addWidget(self.finishGroupBox) # set signals self.connect(self.crsChooseButton, QtCore.SIGNAL('clicked(bool)'), self.getSRS) self.connect(self.bbToMapButton, QtCore.SIGNAL('clicked(bool)'), self.bbToMapBB) self.connect(self.asTxtToMapButton, QtCore.SIGNAL('clicked(bool)'), self.bbToMapTxt) self.connect(actionAddLayer, QtCore.SIGNAL("activated()"), self.addLayer) self.connect(actionZoomIn, QtCore.SIGNAL("activated()"), self.zoomIn) self.connect(actionZoomOut, QtCore.SIGNAL("activated()"), self.zoomOut) self.connect(actionPan, QtCore.SIGNAL("activated()"), self.pan) self.connect(actionIdentify, QtCore.SIGNAL("triggered()"), self.identifyFeature) #load a backdrop layer self.mapCanvasLayers = [] fname = self.path_bkgimg + '/bluemarblemerged.img' fileInfo = QtCore.QFileInfo(fname) baseName = fileInfo.baseName() self.bmLayer = QgsRasterLayer(fname, baseName) QgsMapLayerRegistry.instance().addMapLayer(self.bmLayer) self.cl = QgsMapCanvasLayer(self.bmLayer) self.mapCanvasLayers.append(self.cl) # Set extent to the extent of our layer self.canvas.setExtent(self.bmLayer.extent()) self.canvas.enableAntiAliasing(True) self.canvas.freeze(False) self.canvas.setLayerSet(self.mapCanvasLayers) self.canvas.refresh() #now, add a container layer for our text based/ digitised or selected geoms self.addMemoryLayer() #self.update() def center(self): """TO DO - add docstring""" screen = QtGui.QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) def getSRS(self): # retruns the description and proj4 string of the chosen SRS, from the SRSDialog srsdlg = SRSChooserDialog("Choose SRS") if srsdlg.exec_(): self.crsTextAsProj4.setText(srsdlg.getProjection()) def bbToMapBB(self): self.bbToMap(fullWkt=False) def bbToMapTxt(self): self.bbToMap(fullWkt=True) def bbToMap(self, fullWkt=False): '''takes bounding box coords and puts them on the map''' #if self.foi_type == "AreaOfInterestDefiner": if not fullWkt: ix = self.bbMinXText.text() iy = self.bbMinYText.text() ax = self.bbMaxXText.text() ay = self.bbMaxYText.text() wkt = "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))" % \ (ix, iy, ix, ay, ax, ay, ax, iy, ix, iy) else: wkt = self.asTxtText.toPlainText() try: errnum = 0 geom = QgsGeometry().fromWkt(wkt) print "gotGeom" if self.foi_type == "AreaOfInterestDefiner" and geom.type() != 2: errnum = 1 elif self.foi_type == "LineOfInterestDefiner" and geom.type() != 1: errnum = 1 elif self.foi_type == "PointOfInterestDefiner" and geom.type() != 0: errnum = 1 else: print "attempting to add geometry to mem layer" self.addGeomToMemoryLayer(geom) if errnum == 1: raise ModuleError(self, "Incorrect Geometry Type chosen") except: raise ModuleError(self, "Could not generate Geometry from text provided") #else: #print "Cannot create a Bounding box feature on a line or point layer" #add to map #map tool functions def addLayer(self): """TO DO: Add doc string""" fileName = QtGui.QFileDialog.getOpenFileName( parent=None, caption="Select Vector Overlay Layer", filter="Vector Files (*.shp *.geojson *.gml)") print fileName info = QtCore.QFileInfo(fileName) print info.filePath() print info.completeBaseName() # create layer layer = QgsVectorLayer(info.filePath(), info.completeBaseName(), "ogr") if not layer.isValid(): print "invalid layer" return # add layer to the registry QgsMapLayerRegistry.instance().addMapLayer(layer) # set extent to the extent of our layer #self.canvas.setExtent(layer.extent()) # set the map canvas layer set cl = QgsMapCanvasLayer(layer) self.mapCanvasLayers.insert(len(self.mapCanvasLayers) - 2, cl) #layers = [cl] self.canvas.setLayerSet(self.mapCanvasLayers) print "added Layer" def addMemoryLayer(self): '''Adds a layer to contain the feature defined by a bounding box, wkt, digitised poly|line|point or selection from other layer. ''' foi_type = self.foi_type.lower() if foi_type == 'areaofinterestdefiner': layer = QgsVectorLayer("Polygon", "Area of Interest", "memory") if foi_type == 'lineofinterestdefiner': layer = QgsVectorLayer("Linestring", "Line of Interest", "memory") if foi_type == 'pointofinterestdefiner': layer = QgsVectorLayer("Point", "Point of Interest", "memory") if foi_type == 'areaofinterestdefiner': sym = QgsSymbol(QGis.Polygon) sym.setColor(QtCore.Qt.black) sym.setFillColor(QtCore.Qt.green) sym.setFillStyle(QtCore.Qt.Dense6Pattern) sym.setLineWidth(0.5) sr = QgsSingleSymbolRenderer(QGis.Polygon) if foi_type == 'lineofinterestdefiner': sym = QgsSymbol(QGis.Line) sym.setColor(QtCore.Qt.black) sym.setFillColor(QtCore.Qt.green) sym.setFillStyle(QtCore.Qt.SolidPattern) sym.setLineWidth(0.5) sr = QgsSingleSymbolRenderer(QGis.Line) if foi_type == 'pointofinterestdefiner': sym = QgsSymbol(QGis.Point) sym.setColor(QtCore.Qt.black) sym.setFillColor(QtCore.Qt.green) sym.setFillStyle(QtCore.Qt.SolidPattern) sym.setLineWidth(0.3) sym.setPointSize(4) sym.setNamedPointSymbol("hard:triangle") sr = QgsSingleSymbolRenderer(QGis.Point) sr.addSymbol(sym) layer.setRenderer(sr) if not layer.isValid(): print "invalid layer" return ml_dp = layer.dataProvider() ml_dp.addAttributes([QgsField("gid", QtCore.QVariant.String)]) # add layer to the registry self.mem_layer_obj = QgsMapLayerRegistry.instance().addMapLayer(layer) # set extent to the extent of our layer #self.canvas.setExtent(layer.extent()) # set the map canvas layer set cl = QgsMapCanvasLayer(layer) self.mapCanvasLayers.insert(0, cl) #layers = [cl] self.canvas.setLayerSet(self.mapCanvasLayers) print "added Layer" def addGeomToMemoryLayer(self, the_geom, origin=0, delete_when_done=False): """TO DO: Add doc string""" foi_type = self.foi_type.lower() print "got foi_type" if self.mem_layer_obj.featureCount() > 0: if origin == 1: # is added by identify operation pass else: print self.mem_layer_obj.featureCount() print "there exists a feature, kill it!" self.mem_layer_obj.select() print "Feature count selcted for deletion:" print self.mem_layer_obj.selectedFeatureCount() self.mem_layer_obj.deleteSelectedFeatures() #self.mem_layer_obj.deleteFeature(0) self.mem_layer_obj.commitChanges() self.mem_layer_obj.triggerRepaint() ml_dp = self.mem_layer_obj.dataProvider() print "got DP" uuid_gid = QtCore.QUuid().createUuid().toString() print "got uuid" fet = QgsFeature() print "got feature with id" fet.setGeometry(the_geom) print "set geometry" fet.addAttribute(0, uuid_gid) print "set attr " ml_dp.addFeatures([fet]) self.mem_layer_obj.commitChanges() print "added layers" #self.mem_layer_obj.updateFeatureAttributes(fet) #self.mem_layer_obj.updateFeatureGeometry(fet) self.mem_layer_obj.updateExtents() print "updated extents" #self.mem_layer_obj.drawFeature(fet) self.mem_layer_obj.triggerRepaint() print "trp" return fet.id() def zoomIn(self): """TO DO: Add doc string""" self.canvas.setMapTool(self.toolZoomIn) def zoomOut(self): """TO DO: Add doc string""" self.canvas.setMapTool(self.toolZoomOut) def pan(self): """TO DO: Add doc string""" self.canvas.setMapTool(self.toolPan) def identifyFeature(self): '''getFeatureInfo functionality''' self.canvas.setMapTool(self.toolIdentify) #print "GFI not yet implemented" def gotFeatureForIdentification(self, pos): """Show a dialog with road information """ #pos is a rectangle self.mem_layer_obj.select() ftr = QgsFeature() ftr_ids = [] while self.mem_layer_obj.nextFeature(ftr): if ftr.geometry().intersects(pos): ftr_ids.append(ftr.id()) self.chosenFOIGeoms = [] self.info = QgsMessageViewer() if ftr_ids != []: f = QgsFeature() foi_type = self.foi_type.lower() if foi_type == 'areaofinterestdefiner': ftrData = "You have selected the following feature(s) for use as an Area of Interest:\n\n" if foi_type == 'lineofinterestdefiner': ftrData = "You have selected the following feature(s) for use as a Line of Interest:\n\n" if foi_type == 'pointofinterestdefiner': ftrData = "You have selected the following feature(s) for use as a Point of Interest:\n\n" for fid in ftr_ids: self.mem_layer_obj.dataProvider().featureAtId(fid, f, True) ftrData += f.attributeMap()[0].toString() ftrData += "\n_____________________________\n" self.chosenFOIGeoms.append(f.geometry()) id_fid = self.addGeomToMemoryLayer(f.geometry()) self.info.setMessageAsPlainText(ftrData) else: self.info.setMessageAsPlainText("no data to show") self.info.show() return def makeAOI(self): pass def makeLOI(self): pass def makePOI(self): pass def okTriggered(self): the_fet = QgsFeature() the_geoms = [] print self.mem_layer_obj.featureCount() self.mem_layer_obj.select() while self.mem_layer_obj.nextFeature(the_fet): #self.mem_layer_obj.featureAtId(0, the_fet) the_geoms.append(str(the_fet.geometry().exportToWkt())) print the_geoms wktstr = WKTString() print wktstr wktstr.setValue(the_geoms[0]) self.controller.update_ports_and_functions( self.module.id, [], [], [("WKTGeometry", the_geoms), ("SRS", [self.crsTextAsProj4.text()])]) self.close()