def createMemLayer(line, breaksList): ''' create memory layer storing all reaches :return: ''' # create layer vl = QgsVectorLayer("LineString", "sinuosity_river", "memory") pr = vl.dataProvider() # add fields pr.addAttributes([ QgsField("reach", QVariant.Int), QgsField("sinuosity", QVariant.Double), QgsField("Length", QVariant.Double) ]) vl.updateFields() # create breaks with initial and final bk = sorted(breaksList) bk.insert(0, 0) bk.append(line.length()) for breack in range(1, len(bk)): ptInt = line.interpolate(bk[breack - 1]) ptFin = line.interpolate(bk[breack]) reach = splitLine(line, ptInt, ptFin) # sinuosity calc dist = qgisdist(ptInt, ptFin) lenReach = bk[breack] - bk[breack - 1] # add a feature fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPolylineXY(reach)) fet.setAttributes([breack, lenReach / dist, str(lenReach)]) pr.addFeatures([fet]) #vl.updateExtents() vl.commitChanges() return vl
def getPoint(self, mapPoint): self.set_rad.setEnabled(True) # change tool so you don't get more than one POI self.canvas.unsetMapTool(self.emitPoint) self.canvas.setMapTool(self.userTool) # Get the click if mapPoint: self.atk_pt = QgsPoint(mapPoint) self.distance() # Specify the geometry type layer = QgsVectorLayer('Point?crs=epsg:28992', 'Attack Point', 'memory') style = "style_attack.qml" qml_path = self.plugin_dir + "/data/" + style layer.loadNamedStyle(qml_path) layer.triggerRepaint() # Set the provider to accept the data source prov = layer.dataProvider() # Add a new feature and assign the geometry feat = QgsFeature() feat.setGeometry(QgsGeometry.fromPoint(mapPoint)) prov.addFeatures([feat]) # Update extent of the layer layer.updateExtents() # Add the layer to the Layers panel QgsMapLayerRegistry.instance().addMapLayers([layer])
def dup_layer(self, crs, names): for name in names: layer = uf.getLegendLayerByName(self.iface, "POI_Evacu8") layer_type = {'0': 'Point', '1': 'LineString', '2': 'Polygon'} mem_layer = QgsVectorLayer( layer_type[str(layer.geometryType())] + "?crs=epsg:" + str(crs), name, "memory") feats = [feat for feat in layer.getFeatures()] mem_layer_data = mem_layer.dataProvider() attr = layer.dataProvider().fields().toList() mem_layer_data.addAttributes(attr) mem_layer.updateFields() mem_layer_data.addFeatures(feats) QgsMapLayerRegistry.instance().addMapLayer(mem_layer)
def create_point(self, p1, name): layer = QgsVectorLayer('Point?crs=%s' % int(self.crs), name, "memory") mycrs = QgsCoordinateReferenceSystem(int(self.crs), 0) self.reprojectgeographic = QgsCoordinateTransform( self.iface.mapCanvas().mapRenderer().destinationCrs(), mycrs) pr = layer.dataProvider() point = QgsFeature() point.setGeometry( QgsGeometry.fromPoint(self.reprojectgeographic.transform(p1))) pr.addFeatures([point]) #layer.setCrs(QgsCoordinateReferenceSystem(int(self.crs), 0)) layer.updateExtents() QgsMapLayerRegistry.instance().addMapLayer(layer) return p1
class Create_vlayer(object): '''creation of a virtual layer''' def __init__(self, nom, type): self.type = type self.name = nom self.layer = QgsVectorLayer(self.type, self.name, "memory") self.pr = self.layer.dataProvider() def create_point(self, geometry): # add point to the layer self.seg = QgsFeature() self.seg.setGeometry(QgsGeometry.fromPoint(geometry)) self.pr.addFeatures([self.seg]) self.layer.updateExtents() @property def display_layer(self): #end of layer and display layer QgsProject.instance().addMapLayers([self.layer])
def exit_dialog(self, points, crs): self.dialog.close() layer = QgsVectorLayer('LineString', self.name_tracado, "memory") pr = layer.dataProvider() print points anterior = QgsPoint(points[0]) fets = [] for p in points[1:]: fet = QgsFeature(layer.pendingFields()) fet.setGeometry(QgsGeometry.fromPolyline([anterior, QgsPoint(p)])) fets.append(fet) anterior = QgsPoint(p) pr.addFeatures(fets) self.crs = crs layer.setCrs(QgsCoordinateReferenceSystem(int(crs), 0)) layer.updateExtents() QgsMapLayerRegistry.instance().addMapLayer(layer)
def plotar(self): vl = QgsVectorLayer("Point", "temporary_points", "memory") pr = vl.dataProvider() # Enter editing mode vl.startEditing() # add fields pr.addAttributes([ QgsField("estaca", QVariant.String), QgsField("descrição", QVariant.String), QgsField("north", QVariant.String), QgsField("este", QVariant.String), QgsField("cota", QVariant.String), QgsField("azimite", QVariant.String) ]) fets = [] for r in range(self.tableWidget.rowCount()): ident = self.tableWidget.item(r, 0).text() if ident in ["", None]: break fet = QgsFeature(vl.pendingFields()) n = 0.0 e = 0.0 try: es = self.tableWidget.item(r, 0).text() d = self.tableWidget.item(r, 1).text() n = float(self.tableWidget.item(r, 3).text()) e = float(self.tableWidget.item(r, 4).text()) c = float(self.tableWidget.item(r, 5).text()) a = self.tableWidget.item(r, 6).text() except: break fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(e, n))) fet.setAttributes([es, d, n, e, c, a]) fets.append(fet) pr.addFeatures(fets) vl.commitChanges() QgsMapLayerRegistry.instance().addMapLayer(vl)
def run(self): QgsMessageLog.logMessage(f'Started task {self.description()}', 'TracingCAJ', Qgis.Info) epsg = self.__hidrometers.crs().postgisSrid() uri = "LineString?crs=epsg:" + str( epsg ) + "&field=id:integer" "&field=distance:double(20,2)&index=yes" dist = QgsVectorLayer(uri, 'dist', 'memory') QgsProject.instance().addMapLayer(dist) prov = dist.dataProvider() points_features = [ point_feature for point_feature in self.__hidrometers.getFeatures() ] feats = [] if len(points_features) > 0: for p in points_features: nearest_pipe = self.find_nearest_pipelines(p.geometry()) try: minDistPoint = nearest_pipe.closestSegmentWithContext( p.geometry().asPoint())[1] feat = QgsFeature() feat.setGeometry( QgsGeometry.fromPolylineXY( [p.geometry().asPoint(), minDistPoint])) feat.setAttributes( [points_features.index(p), feat.geometry().length()]) feats.append(feat) except Exception as e: print(p.id()) prov.addFeatures(feats)
def generate_and_load_geopackage_layer(self, gpkg_file, crs=None, type="Point", name="source_indicators", fields=dict(name="unit_name", type=QVariant.String)): vl = QgsVectorLayer(type, name, "memory") pr = vl.dataProvider() for field in fields: pr.addAttributes([QgsField(field[0], field[1])]) vl.updateFields() if crs is not None: vl.setCrs(crs) from mappy.mappy_utils import write_layer_to_gpkg2, add_layer_from_geopackage write_layer_to_gpkg2(vl, gpkg_file, name) # vector_file = vector_file.as_posix() + f"|layername={vl.name()}" # print(vector_file) # l = QgsVectorLayer(vector_file) # l.setName(vl.name()) l = add_layer_from_geopackage(gpkg_file, name) return l
def drawCurva(self): if not hasattr(self.c, "dados"): self.c.dados = [] self.comboCurva: QtWidgets.QComboBox layer = QgsVectorLayer( 'LineString?crs=%s' % (QgsProject.instance().crs().authid()), "Curva: " + str(self.comboCurva.currentText()), "memory") layer.setCrs( QgsCoordinateReferenceSystem(QgsProject.instance().crs())) layer.renderer().symbol().setWidth(.5) layer.renderer().symbol().setColor(QtGui.QColor("#0f16d0")) layer.triggerRepaint() fields = layerFields() layer.dataProvider().addAttributes(fields) layer.updateFields() QgsProject.instance().addMapLayer(layer, False) QgsProject.instance().layerTreeRoot().insertLayer(0, layer) self.c.layer = layer layer = self.c.layer layer.dataProvider().deleteFeatures( [f.id() for f in layer.getFeatures()]) vmax = 0 k = 0 i = -1 data = None try: if hasattr(self, "justStarted") and self.justStarted: for tipo, index, state in self.c.readData(): i += 1 if tipo == "C": data = circleArc2(layer, state, index, self.layer, self.next_index) k = 0 vmax = "120 km/h" elif tipo == "EC": data = polyTransCircle(layer, state, index, self.layer, self.next_index, self.current_index) k = 0 vmax = "120 km/h" elif tipo == "EE": data = inSpiral2(layer, state, index, self.layer, self.next_index) k = 0 vmax = "120 km/h" elif tipo == "ES": data = outSpiral2(layer, state, index, self.layer, self.next_index) k = 0 vmax = "120 km/h" elif tipo == "T": data = tangent2(layer, state, index, self.layer, self.next_index) k = 0 vmax = "120 km/h" else: continue if len(self.c.dados) - 1 < i: self.c.dados.append(None) self.c.dados[i] = tipo, data else: for tipo, index, state in self.c.readData(): i += 1 if tipo == "C": data = circleArc(layer, state, index, self.layer, self.next_index, self.current_index) k = 0 vmax = "120 km/h" elif tipo == "EC": data = polyTransCircle(layer, state, index, self.layer, self.next_index, self.current_index) k = 0 vmax = "120 km/h" elif tipo == "EE": data = inSpiral(layer, state, index, self.layer, self.next_index) k = 0 vmax = "120 km/h" elif tipo == "ES": data = outSpiral(layer, state, index, self.layer, self.next_index) k = 0 vmax = "120 km/h" elif tipo == "T": data = tangent(layer, state, index, self.layer, self.next_index) k = 0 vmax = "120 km/h" else: continue if len(self.c.dados) - 1 < i: self.c.dados.append(None) self.c.dados[i] = tipo, data except Exception as e: messageDialog(title="Erro", message="Não foi possível definir a geometria", info="Provavelmente houve a interseção de curvas") msgLog(str(traceback.format_exception(None, e, e.__traceback__))) self.curvaFailed = True refreshCanvas(self.iface, layer) #TODO compute vmax and k if self.c.lastWidget and data: self.c.lastWidget.fill(data, k=k, vmax=vmax)
def painting(self, data, fileType): currentInputCRS = self.dlg.inputCRS.text().replace(" ", "") table = data.sheets()[0] nrows = table.nrows if fileType == '4G': vl = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"4G基础信息图层", "memory") vlLabel = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"4G基础信息标签层", "memory") elif fileType == '3G': vl = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"3G基础信息图层", "memory") vlLabel = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"3G基础信息标签层", "memory") elif fileType == '2G': vl = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"2G基础信息图层", "memory") vlLabel = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"2G基础信息标签层", "memory") pr = vl.dataProvider() vlLabelPr = vlLabel.dataProvider() attrs = self.createAttributesTable(fileType) pr.addAttributes(attrs) vlLabelPr.addAttributes(attrs) vl.updateFields() vlLabel.updateFields() fet = QgsFeature() self.dlg.progressBar.setVisible(True) '''开始读取到内存''' list = [[] for row in range(nrows-1)] for i in range(nrows): if i > 0: try: if fileType == '4G': for j in range(21): list[i - 1].append(table.cell(i, j).value) if j == 20: list[i - 1].append(table.cell(i, 13).value % 3) if fileType == '3G': for j in range(73): list[i - 1].append(table.cell(i, j).value) if j == 72: list[i - 1].append(int(table.cell(i, 5).value) % 3) if fileType =='2G': for j in range(67): list[i - 1].append(table.cell(i, j).value) if j == 66: list[i - 1].append(int(table.cell(i, 2).value) % 3) except: self.showErrorDialog(u'文档读取出错', u'文档可能存在错误或格式不符合规范') self.dlg.progressBar.setVisible(False) return '''完成读取到内存''' PCI_Types = { '0': ('#F49ECC', 'Mod3=0'), '1': ('#65F0FF', 'Mod3=1'), '2': ('#00FF00', 'Mod3=2'), '3': ('#000', u'未知值'), } categories = [] for pci_type, (color, label) in PCI_Types.items(): symbol = QgsSymbolV2.defaultSymbol(vl.geometryType()) # symbol = QgsFillSymbolV2.createSimple({'color': color, 'color_border': color, 'width_border': '2'}) symbol.setColor(QColor(color)) # symbol.symbolLayer(0).setOutlineColor(QColor('#75263b')) category = QgsRendererCategoryV2(pci_type, symbol, label) categories.append(category) for i in range(len(list)): fetAttrs =[] if fileType == '4G': for j in range(22): fetAttrs.append(list[i][j]) elif fileType == '3G': for j in range(74): fetAttrs.append(list[i][j]) elif fileType == '2G': for j in range(68): fetAttrs.append(list[i][j]) fet.setAttributes(fetAttrs) if fileType == '4G': Longitude = 11 Latitude = 12 Azimuth = list[i][14] elif fileType == '3G': Longitude = 12 Latitude = 13 Azimuth = list[i][15] elif fileType == '2G': Longitude = 15 Latitude = 16 Azimuth = list[i][5] points = [QgsPoint(list[i][Longitude], list[i][Latitude])] # start point startAngle = -20 endAngle = 20 while startAngle <= endAngle: # midway points points.append(QgsPoint(list[i][Longitude] + 0.001 * math.sin(math.radians(Azimuth + startAngle)), list[i][Latitude] + 0.001 * math.cos(math.radians(Azimuth + startAngle)))) startAngle += 2 points.append(QgsPoint(list[i][Longitude], list[i][Latitude])) # end point # create the renderer and assign it to a layer expression = 'Mod3' # field name renderer = QgsCategorizedSymbolRendererV2(expression, categories) vl.setRendererV2(renderer) fet.setGeometry(QgsGeometry.fromPolygon([points])) pr.addFeatures([fet]) # fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(Longitude, Latitude))) vlLabelPr.addFeatures([fet]) vlLabel.setLayerTransparency(100) vl.updateExtents() vlLabel.updateExtents() vl.commitChanges() vlLabel.commitChanges() vl.updateFields() vlLabel.updateFields() if i % 200 == 0: print 'progress:', float(pr.featureCount()) / nrows * 100 self.dlg.progressBar.setValue(float(pr.featureCount()) / nrows * 100.0) palyr = QgsPalLayerSettings() # palyr.readFromLayer(vl) palyr.enabled = True palyr.fieldName = 'CellName' if fileType =='2G': palyr.fieldName = 'CELL_NAME' palyr.placement = QgsPalLayerSettings.OverPoint # palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,False,False,'','') palyr.writeToLayer(vlLabel) QgsMapLayerRegistry.instance().addMapLayer(vl) QgsMapLayerRegistry.instance().addMapLayer(vlLabel) print 'progress:', 100 self.dlg.progressBar.setValue(0) self.dlg.progressBar.setVisible(False) self.iface.messageBar().clearWidgets() qgis.utils.iface.setActiveLayer(vl) self.saveEPSGChange() self.dlg.close()
def ltefpsOKBtn(self): currentInputCRS = self.dlg.inputCRS.text().replace(" ", "") try: sourceLayer = QgsMapLayerRegistry.instance().mapLayersByName(u'4G基础信息图层')[0] except: self.showErrorDialog(u'未找到图层', u'请检查是否已加载“4G基础信息图层”') return try: inputFreq = int(self.ltefpsdlg.inputFreq.text()) inputPCI = int(self.ltefpsdlg.inputPCI.text()) except: self.showErrorDialog(u'错误的输入', u'请输入数字') return # 隐藏之前的同名图层 try: sameLayers = QgsMapLayerRegistry.instance().mapLayersByName(u'4G图层频点PCI查找') for oneLayer in sameLayers: qgis.utils.iface.legendInterface().setLayerVisible(oneLayer, False) except: pass ltefpsLayer = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"4G图层频点PCI查找", "memory") ltefpsPr = ltefpsLayer.dataProvider() ltefpsPr.addAttributes(self.createAttributesTable('4GFreqPCISearch')) ltefpsLayer.updateFields() qgis.utils.iface.legendInterface().setLayerVisible(sourceLayer, False) ltefpsFet = QgsFeature() PCI_Types = { 1: ('#FFFF00', u'频点='+str(inputFreq)+',PCI='+str(inputPCI)), 0: ('#EEEEEE', u'无关频点PCI') } categories = [] for pci_type, (color, label) in PCI_Types.items(): symbol = QgsSymbolV2.defaultSymbol(ltefpsLayer.geometryType()) symbol.setColor(QColor(color)) category = QgsRendererCategoryV2(pci_type, symbol, label) categories.append(category) # 创建属性表 fetAttrs = [] relatedAttrs = [] Longitude, Latitude, Azimuth = 11, 12, 14 for feature in sourceLayer.getFeatures(): attrs = feature.attributes() if (inputFreq == attrs[9]) & (inputPCI == int(attrs[13])): temp = [] for j in range(21): temp.append(attrs[j]) temp.append(1) relatedAttrs.append(temp) else: temp = [] for j in range(21): temp.append(attrs[j]) temp.append(0) fetAttrs.append(temp) for one in relatedAttrs: fetAttrs.append(one) for fetAttr in fetAttrs: ltefpsFet.setAttributes(fetAttr) # 开始画图 points = [QgsPoint(fetAttr[Longitude], fetAttr[Latitude])] # start point startAngle = -20 endAngle = 20 while startAngle <= endAngle: points.append( QgsPoint(fetAttr[Longitude] + 0.001 * math.sin(math.radians(fetAttr[Azimuth] + startAngle)), fetAttr[Latitude] + 0.001 * math.cos(math.radians(fetAttr[Azimuth] + startAngle)))) startAngle += 2 points.append(QgsPoint(fetAttr[Longitude], fetAttr[Latitude])) # end point ltefpsFet.setGeometry(QgsGeometry.fromPolygon([points])) ltefpsPr.addFeatures([ltefpsFet]) # 根据字段值渲染颜色 expression = 'FreqPCI' # field name renderer = QgsCategorizedSymbolRendererV2(expression, categories) ltefpsLayer.setRendererV2(renderer) ltefpsLayer.updateExtents() ltefpsLayer.commitChanges() ltefpsLayer.updateFields() # 更新图层 QgsMapLayerRegistry.instance().addMapLayer(ltefpsLayer) self.ltefpsdlg.close() self.saveEPSGChange() self.dlg.close()
def gsmfsOKBtn(self): currentInputCRS = self.dlg.inputCRS.text().replace(" ", "") inputFreq = self.gsmfsdlg.inputFreq.text() try: sourceLayer = QgsMapLayerRegistry.instance().mapLayersByName(u'2G基础信息图层')[0] except: self.showErrorDialog(u'未找到图层', u'请检查是否已加载“2G基础信息图层”') return # 隐藏之前的同名图层 try: sameLayer = QgsMapLayerRegistry.instance().mapLayersByName(u'2G图层频点查找') for oneLayer in sameLayer: qgis.utils.iface.legendInterface().setLayerVisible(oneLayer, False) except: pass gsmfsLayer = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"2G图层频点查找", "memory") gsmfsPr = gsmfsLayer.dataProvider() gsmfsPr.addAttributes(self.createAttributesTable('2GFreqSearch')) gsmfsLayer.updateFields() # QgsMapLayerRegistry.instance().addMapLayer(gsmfsLayer) qgis.utils.iface.legendInterface().setLayerVisible(sourceLayer, False) gsmfsFet = QgsFeature() try: inputFreq.replace(" ", "") B = int(inputFreq) except: self.showErrorDialog(u'错误的输入', u'请输入数字') return A = B - 1 C = B + 1 PCI_Types = { A: ('#FF63F2', u'频点='+ str(A)), B: ('#FFFF00', u'指定频点='+ str(B)), C: ('#01FF8D', u'频点='+ str(C)), '-1': ('#eeeeee', u'无关频点') } categories = [] for pci_type, (color, label) in PCI_Types.items(): symbol = QgsSymbolV2.defaultSymbol(gsmfsLayer.geometryType()) symbol.setColor(QColor(color)) category = QgsRendererCategoryV2(pci_type, symbol, label) categories.append(category) # 创建属性表 fetAttrs = [] relatedAttrs = [] Longitude, Latitude, Azimuth = 15, 16, 5 for feature in sourceLayer.getFeatures(): attrs = feature.attributes() if (int(inputFreq) == attrs[3]): temp = [] for j in range(67): temp.append(attrs[j]) temp.append(B) relatedAttrs.append(temp) elif int(inputFreq) == int(attrs[3]) - 1: temp = [] for j in range(67): temp.append(attrs[j]) temp.append(A) relatedAttrs.append(temp) elif int(inputFreq) == int(attrs[3]) + 1: temp = [] for j in range(67): temp.append(attrs[j]) temp.append(C) relatedAttrs.append(temp) else: temp = [] for j in range(67): temp.append(attrs[j]) if j == 66: if (int(inputFreq) != attrs[3]) & (int(inputFreq) != int(attrs[3])-1) & (int(inputFreq) != int(attrs[3])+1): temp.append('-1') fetAttrs.append(temp) for one in relatedAttrs: fetAttrs.append(one) for fetAttr in fetAttrs: gsmfsFet.setAttributes(fetAttr) #开始画图 points = [QgsPoint(fetAttr[Longitude], fetAttr[Latitude])] # start point startAngle = -20 endAngle = 20 while startAngle <= endAngle: points.append(QgsPoint(fetAttr[Longitude] + 0.001 * math.sin(math.radians(fetAttr[Azimuth] + startAngle)), fetAttr[Latitude] + 0.001 * math.cos(math.radians(fetAttr[Azimuth] + startAngle)))) startAngle += 2 points.append(QgsPoint(fetAttr[Longitude], fetAttr[Latitude])) # end point gsmfsFet.setGeometry(QgsGeometry.fromPolygon([points])) gsmfsPr.addFeatures([gsmfsFet]) #根据字段值渲染颜色 expression = 'Condition' # field name renderer = QgsCategorizedSymbolRendererV2(expression, categories) gsmfsLayer.setRendererV2(renderer) gsmfsLayer.updateExtents() gsmfsLayer.commitChanges() gsmfsLayer.updateFields() QgsMapLayerRegistry.instance().addMapLayer(gsmfsLayer) self.gsmfsdlg.close() self.saveEPSGChange() self.dlg.close()
def executeCropRowsClipProcessing(self): """Execute Crop Rows STEP 1""" QgsMessageLog.logMessage( 'Excecute Task1: Clip Raster Mosaic by Vector Mask') strMosaicRasterFileSelected = self.dlg.comboBoxInputRaster.currentText( ) strMaskVectorFileSelected = self.dlg.comboBoxInputVector.currentText() seedValue = 0 QgsMessageLog.logMessage('Get Seed from user selection') if self.dlg.radioButtonSeed1.isChecked() == True: seedValue = 1 elif self.dlg.radioButtonSeed2.isChecked() == True: seedValue = 2 elif self.dlg.radioButtonSeed3.isChecked() == True: seedValue = 3 elif self.dlg.radioButtonSeed4.isChecked() == True: seedValue = 4 if (seedValue == 0): QgsMessageLog.logMessage('You must be set a seed value !') QMessageBox.critical(None, 'Error!', "You must be set a <b>seed</b> value !", QMessageBox.Ok) pass else: QgsMessageLog.logMessage('Seed value: ' + str(seedValue)) #Start Crop Rows processing if strMosaicRasterFileSelected != '' and strMaskVectorFileSelected != '' and seedValue > 0 and self.flagClipTaskDone == 0: if self.flagNoCropRaster == False: msgboxCrop = "Are you sure that you want to start a <b>Mosaic Clip by Mask</b> process?<br>Keep in mind this task can take a few minutes, even several hours." else: msgboxCrop = "Are you sure that you want to copy a raster <b>Mosaic</b> into a selected shared folder?<br>Keep in mind this process can take a few minutes, even several hours." ret = QMessageBox.question(None, "Mosaic Data Preprocessing", (msgboxCrop), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if ret == QMessageBox.Yes: #hide step1 button self.dlg.btnExecuteClippingTask.setVisible(False) QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) self.dlg.statusBarProcessing.setGeometry(10, 281, 631, 31) self.dlg.statusBarProcessing.setValue(1) QgsMessageLog.logMessage('Processing Raster ') #urlSourceRasterMosaic = QgsMapLayerRegistry.instance().mapLayersByName(strMosaicRasterFileSelected)[0].dataProvider().dataSourceUri() urlSourceRasterMosaic = QgsProject.instance().mapLayersByName( strMosaicRasterFileSelected)[0].dataProvider( ).dataSourceUri() self.dlg.statusBarProcessing.setValue(5) #urlSourceVectorMask = QgsMapLayerRegistry.instance().mapLayersByName(strMaskVectorFileSelected)[0].dataProvider().dataSourceUri() urlSourceVectorMask = QgsProject.instance().mapLayersByName( strMaskVectorFileSelected)[0].dataProvider().dataSourceUri( ) self.dlg.statusBarProcessing.setValue(10) urlSourceVectorMaskSplit = urlSourceVectorMask.split("|")[0] self.dlg.statusBarProcessing.setValue(20) temporalPath = self.dlg.inputSharedFolderPath.text().replace( "/", "\\") rasterLyr = QgsRasterLayer(urlSourceRasterMosaic, "masklayer") pixelSizeX = rasterLyr.rasterUnitsPerPixelX() pixelSizeY = rasterLyr.rasterUnitsPerPixelY() self.dlg.statusBarProcessing.setValue(25) QgsMessageLog.logMessage(str(urlSourceRasterMosaic)) QgsMessageLog.logMessage(str(urlSourceVectorMaskSplit)) QgsMessageLog.logMessage('GDAL Clipper') QgsMessageLog.logMessage(str(pixelSizeX)) QgsMessageLog.logMessage(str(pixelSizeY)) gdalOSGeoPath = self.dlg.inputGdalOsgeoPath.text().replace( "/", "\\") #temporalPath = self.dlg.inputSharedFolderPath.text().replace("/", "\\") self.dlg.statusBarProcessing.setValue(30) timestr = time.strftime("%Y%m%d-%H%M%S") ouputFilenameRasterClip = 'clipfile_' + timestr + '.tif' ouputFilenameVectorMask = 'maskfile_' + timestr + '.shp' ouputFilenamePrj = 'croprows_' + timestr ouputFilenameCropRowsProjectXML = 'croprows_' + timestr + '.xml' ouputclipfile_path = os.path.join(temporalPath, ouputFilenameRasterClip) #temporalPath.replace("/", "\\") + ouputFilenameRasterClip self.dlg.statusBarProcessing.setValue(35) if self.flagNoCropRaster == True: QgsMessageLog.logMessage( 'No Crop option selected - Copy file directly') shutil.copyfile( urlSourceRasterMosaic, os.path.join(ouputclipfile_path[:-4] + '.tif')) self.dlg.statusBarProcessing.setValue(40) else: QgsMessageLog.logMessage( 'Crop raster by mask option selected - Cliping using GDAL' ) #print('C:/Program Files/QGIS 2.14/bin/gdalwarp') gdalWarpSubProcessCommand = '"' + gdalOSGeoPath + "\\" + 'gdalwarp.exe" -dstnodata -9999 -q -cutline ' + urlSourceVectorMaskSplit.replace( "/", "\\") + ' -crop_to_cutline -tr ' + str( pixelSizeX) + ' ' + str( pixelSizeX ) + ' -of GTiff ' + urlSourceRasterMosaic.replace( "/", "\\") + ' ' + ouputclipfile_path QgsMessageLog.logMessage(str(gdalWarpSubProcessCommand)) self.dlg.statusBarProcessing.setValue(40) p = subprocess.Popen(gdalWarpSubProcessCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print(line), retval = p.wait() self.dlg.statusBarProcessing.setValue(50) QgsMessageLog.logMessage( 'Clipper process done check result file ' + ouputclipfile_path) #Load result file into map environment rasterLayerClipped = QgsRasterLayer( ouputclipfile_path, ouputFilenameRasterClip[:-4]) pixelSizeXClip = rasterLayerClipped.rasterUnitsPerPixelX() pixelSizeYClip = rasterLayerClipped.rasterUnitsPerPixelY() imageWClip = rasterLayerClipped.width() imageHClip = rasterLayerClipped.height() providerRasterLayerClipped = rasterLayerClipped.dataProvider() extentRasterLayerClipped = rasterLayerClipped.extent() #print(providerRasterLayerClipped) #xmin,ymax,xmax,ymin imageXminClip = (extentRasterLayerClipped.xMinimum()) imageYminClip = (extentRasterLayerClipped.yMinimum()) imageXmaxClip = (extentRasterLayerClipped.xMaximum()) imageYmaxClip = (extentRasterLayerClipped.yMaximum()) #origin imageXOriginClip = int( round(extentRasterLayerClipped.xMinimum())) imageYOriginClip = int( round(extentRasterLayerClipped.yMinimum())) #epsg proj4crs = rasterLayerClipped.crs() QgsMessageLog.logMessage(str(proj4crs.srsid())) QgsMessageLog.logMessage(str(proj4crs.toProj4())) QgsMessageLog.logMessage(str(proj4crs.authid())) QgsMessageLog.logMessage(str(proj4crs.description())) QgsMessageLog.logMessage(str(proj4crs.ellipsoidAcronym())) QgsMessageLog.logMessage(str(proj4crs.findMatchingProj())) QgsMessageLog.logMessage(str(proj4crs.postgisSrid())) QgsMessageLog.logMessage(str(proj4crs.toWkt())) epsgClip = proj4crs.postgisSrid() epsgWKTClip = proj4crs.toWkt() #QgsMapLayerRegistry.instance().addMapLayer(rasterLayerClipped) QgsProject.instance().addMapLayer(rasterLayerClipped) #pass self.dlg.statusBarProcessing.setValue(75) #copy vector mask outputFileMaskPath = os.path.join(temporalPath, ouputFilenameVectorMask) #temporalPath.replace("/", "\\") + ouputFilenameVectorMask temporalVectorLayer = QgsVectorLayer(urlSourceVectorMaskSplit, "tmp_polygon", "ogr") shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.shp', os.path.join(outputFileMaskPath[:-4] + '.shp')) shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.dbf', os.path.join(outputFileMaskPath[:-4] + '.dbf')) shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.shx', os.path.join(outputFileMaskPath[:-4] + '.shx')) temporalVectorLayerDataProvider = temporalVectorLayer.dataProvider( ) temporalVectorLayerCrs = temporalVectorLayerDataProvider.crs() temporalVectorLayerCrsString = temporalVectorLayerCrs.authid() temporalVectorLayerEPSGInt = int( temporalVectorLayerCrsString[5:]) QgsMessageLog.logMessage(str(temporalVectorLayerEPSGInt)) maskVectorLayerExported = QgsVectorLayer( outputFileMaskPath, ouputFilenameVectorMask[:-4], "ogr") crs = maskVectorLayerExported.crs() crs.createFromId(temporalVectorLayerEPSGInt) maskVectorLayerExported.setCrs(crs) maskVectorLayerExported.setCrs( QgsCoordinateReferenceSystem( temporalVectorLayerEPSGInt, QgsCoordinateReferenceSystem.EpsgCrsId)) styleBoundary = os.path.join( (os.path.dirname(os.path.abspath(__file__))), 'styles', 'croprows_style_boundary.qml') maskVectorLayerExported.loadNamedStyle(styleBoundary) #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerExported) QgsProject.instance().addMapLayer(maskVectorLayerExported) #end copy vector mask #TODO: try not to simulate process status, make it real for i in range(76, 90): self.dlg.statusBarProcessing.setValue(i) #show step2 button self.dlg.btnExecuteProcessingFromApi.setVisible(True) self.dlg.statusBarProcessing.setValue(95) arrXMLOptions = [ str(seedValue), str(ouputFilenameRasterClip), str(ouputFilenameVectorMask), str(pixelSizeXClip) + ',-' + str(pixelSizeYClip), str(imageWClip) + ',' + str(imageHClip), str(imageXminClip) + ',' + str(imageYminClip) + ',' + str(imageXmaxClip) + ',' + str(imageYmaxClip), str(imageXOriginClip) + ',' + str(imageYOriginClip), str(epsgClip), str(epsgWKTClip), str(ouputFilenamePrj) ] #Write XML file self.writeXMLFile(ouputFilenameCropRowsProjectXML, arrXMLOptions) self.dlg.xmlCoreFile.setText( str(ouputFilenameCropRowsProjectXML)) self.dlg.statusBarProcessing.setValue(100) QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor) self.flagClipTaskDone = 1 toStep2Msg = QMessageBox.question( None, "Crop Rows processing task start", ("Are you sure that you want to start a <b>Crop Rows</b> processing task ?<br>Keep in mind this process can take a few minutes, even several hours.<br><br>Make sure that <b>Crop Rows - API Server is Running before continue.</b>" ), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if toStep2Msg == QMessageBox.Yes: QgsMessageLog.logMessage('Run Step 2') self.executeCropRowsProcessingFromAPI() pass else: QMessageBox.information( None, 'Message !', "You must be run the processing task by manually way !<br>Just click on the button <b>Processing Task (manual)</b>", QMessageBox.Ok) pass else: QgsMessageLog.logMessage('No Mosaic Clip Process Selected') pass else: QgsMessageLog.logMessage('Missing Required Parameters') QgsMessageLog.logMessage('strMosaicRasterFileSelected: ' + strMosaicRasterFileSelected) QgsMessageLog.logMessage('strMaskVectorFileSelected: ' + strMaskVectorFileSelected) QgsMessageLog.logMessage('seedValue: ' + str(seedValue)) QgsMessageLog.logMessage('flagClipTaskDone: ' + str(self.flagClipTaskDone)) QMessageBox.critical(None, 'Error!', "Missing Required Parameter !", QMessageBox.Ok)