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 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 carregacarta(self, model): # create Qt widget canvas = self.iface.mapCanvas() #canvas.setCanvasColor(Qt.black) # enable this for smooth rendering canvas.enableAntiAliasing(True) # not updated US6SP10M files from ENC_ROOT source_dir = QtGui.QFileDialog.getExistingDirectory( None, 'Select a folder:', '', QtGui.QFileDialog.ShowDirsOnly) if source_dir in [None, '']: return # source_dir = "/home/lucas/python_work/TopoGraph" canvas_layers = [] extent = QgsRectangle() extent.setMinimal() # load vector layers registry = QgsMapLayerRegistry.instance() try: os.mkdir(r"%s/tmp" % (source_dir)) except: pass for files in os.listdir(source_dir): # load only the shapefiles if files.endswith(".dxf") or files.endswith( ".shp") or files.endswith(".dgn"): vlayer = QgsVectorLayer(source_dir + "/" + files, files, "ogr") # add layer to the registry #registry.addMapLayer(vlayer) #extent.combineExtentWith(vlayer.extent()) #canvas_layers.append(QgsMapCanvasLayer(vlayer)) writer = QgsVectorFileWriter.writeAsVectorFormat( vlayer, r"%s/tmp/%s.shp" % (source_dir, files), "utf-8", None, "ESRI Shapefile") vlayer = QgsVectorLayer(r"%s/tmp/%s.shp" % (source_dir, files), files, "ogr") attr = {} vlayerUser = vlayer.crs().toProj4() for elem in vlayerUser.strip().split('+'): key_value = elem.strip().split('=') if len(key_value) > 1: attr[key_value[0]] = key_value[1] else: attr[key_value[0]] = None attr['units'] = Config.UNITS string_proj = '' for a in attr: if a == '': continue if attr[a] is None: string_proj += '+%s ' % a else: string_proj += '+%s=%s ' % (a, attr[a]) crs = QgsCoordinateReferenceSystem() crs.createFromProj4(string_proj) vlayer.setCrs(crs) registry.addMapLayer(vlayer) extent.combineExtentWith(vlayer.extent()) canvas_layers.append(QgsMapCanvasLayer(vlayer)) print writer # set extent to the extent of our layer # canvas.setExtent(vlayer.extent()) # set the map canvas layer set # canvas.setLayerSet([QgsMapCanvasLayer(vlayer)]) canvas.setExtent(extent) canvas.setLayerSet(canvas_layers)
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 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)