def points_interet(POI_EPSG, Isochrone10V, param): poi = iface.addVectorLayer("POI_EPSG", "POI", "ogr") iso10v = iface.addVectorLayer("Isochrone10V", "isochrone10v", "ogr") poi.removeSelection() processing.runalg('qgis:extractbylocation', poi, iso10v, u'within', 0, ".\POIiso.shp") POIiso = iface.addVectorLayer(".\POIiso.shp", "POIiso", "ogr") nombre_POI = POIiso.featureCount() flag = 0 while flag not in [1, 2, 3]: flag = raw_input( 'Veuillez entrer le numero correspondant a la repartition des points d\'interet, puis valider avec Entree : \n1:uniforme autour du quartier \n2:homogène autour du quartier \n3:concentrée d\'un seul côté du quartier \n' ) rep = flag flag = 0 while flag not in [1, 2, 3]: flag = raw_input( 'Veuillez entrer le numero correspondant a la proximite des points d\'interet, puis valider avec Entree : \n1:la plupart des points sont proches du quartier \n2: points à distances moyennes ou hétérogènes du quartier \n3:points éloignés du quartier \n' ) pro = flag QgsMapLayerRegistry.instance().removeMapLayers([poi.id()]) QgsMapLayerRegistry.instance().removeMapLayers([iso10v.id()]) QgsMapLayerRegistry.instance().removeMapLayers([POIiso.id()]) return param['R{0}'.format(rep)] * param['PR{0}'.format(pro)] * nombre_POI
def saveV(self,parameters): if os.path.isfile(parameters['OUTPUT']): os.remove(parameters['OUTPUT']) # set up the shapefile driver # create fields layerFields = QgsFields() layerFields.append(QgsField('IDs', QVariant.Int)) layerFields.append(QgsField('real', QVariant.Double)) layerFields.append(QgsField('max', QVariant.Double)) layerFields.append(QgsField('min', QVariant.Double)) layerFields.append(QgsField('std', QVariant.Double)) layerFields.append(QgsField('sum', QVariant.Double)) layerFields.append(QgsField('average', QVariant.Double)) layerFields.append(QgsField('mean', QVariant.Double)) #layerFields.append(QgsField('range', QVariant.Double)) fn = parameters['OUTPUT'] writer = QgsVectorFileWriter(fn, 'UTF-8', layerFields, QgsWkbTypes.Point, QgsCoordinateReferenceSystem('EPSG:3857')) for i in range(len(parameters['INPUT2'])): feat = QgsFeature() feat.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(float(parameters['INPUT2'][i,0]) , float(parameters['INPUT2'][i,1])))) l=[] l=[i] #print(parameters['INPUT3'],'input3') #print(l+parameters['INPUT3'][i],'MIO') feat.setAttributes(l+parameters['INPUT3'][i]) writer.addFeature(feat) del(writer) iface.addVectorLayer(fn, '', 'ogr')
def show_shapefile_layers(directory): """ Show the manholes, pipes and measuring points layer. Set the manholes layer as active layer to be the same layer as the active tab. Arguments: (string) directory: Directory where the shapefiles are. These shapefiles are shown as layers. """ # Manholes manholes_filename = "{}.shp".format(SHP_NAME_MANHOLES) manholes_path = os.path.join(directory, manholes_filename) manholes_layer = iface.addVectorLayer(manholes_path, SHP_NAME_MANHOLES, "ogr") # Pipes pipes_filename = "{}.shp".format(SHP_NAME_PIPES) pipes_path = os.path.join(directory, pipes_filename) pipes_layer = iface.addVectorLayer(pipes_path, SHP_NAME_PIPES, "ogr") # Measuring stations measuring_points_filename = "{}.shp".format(SHP_NAME_MEASURING_POINTS) measuring_points_path = os.path.join(directory, measuring_points_filename) measuring_points_layer = iface.addVectorLayer(measuring_points_path, SHP_NAME_MEASURING_POINTS, "ogr") # Set manholes layer as active layer iface.setActiveLayer(manholes_layer)
def load(self, crs, idSubgrupo = None): vlayerQml = os.path.join(self.abstractDb.getQmlDir(), self.qmlName+'.qml') database = self.abstractDb.db.databaseName() vlayer = iface.addVectorLayer(self.uri.uri(), self.layer_name, self.provider) if not vlayer: return None vlayer.setCrs(crs) if self.schema <> 'views': vlayer.loadNamedStyle(vlayerQml, False) attrList = vlayer.pendingFields() for field in attrList: i = vlayer.fieldNameIndex(field.name()) if vlayer.editorWidgetV2(i) == 'ValueRelation': groupList = iface.legendInterface().groups() groupRelationshipList = iface.legendInterface().groupLayerRelationship() filename = os.path.basename(database).split('.')[0] if filename not in groupList: idx = iface.legendInterface().addGroup(filename, True,-1) domainIdGroup = iface.legendInterface().addGroup(self.tr("Dominios"), True, idx) else: idx = groupList.index(filename) if "Dominios" not in groupList[idx::]: domainIdGroup = iface.legendInterface().addGroup(self.tr("Dominios"), True, idx) else: domainIdGroup = groupList[idx::].index("Dominios") valueRelationDict = vlayer.editorWidgetV2Config(i) domainTableName = valueRelationDict['Layer'] loadedLayers = iface.legendInterface().layers() domainLoaded = False for ll in loadedLayers: if ll.name() == domainTableName: candidateUri = QgsDataSourceURI(ll.dataProvider().dataSourceUri()) if database == candidateUri.database(): domainLoaded = True domLayer = ll if not domainLoaded: uri = QgsDataSourceURI() uri.setDatabase(database) uri.setDataSource('', 'dominios_'+domainTableName, None) #TODO Load domain layer into a group domLayer = iface.addVectorLayer(uri.uri(), domainTableName, self.provider) iface.legendInterface().moveLayer(domLayer, domainIdGroup) valueRelationDict['Layer'] = domLayer.id() vlayer.setEditorWidgetV2Config(i,valueRelationDict) self.qmlLoaded.emit() iface.legendInterface().moveLayer(vlayer, idSubgrupo) if not vlayer.isValid(): QgsMessageLog.logMessage(vlayer.error().summary(), "DSG Tools Plugin", QgsMessageLog.CRITICAL) return vlayer
def run(polygonLayer, projFolder): # Shape file loader newPolygonLayer = copyMainLayer(polygonLayer, projFolder) source = newPolygonLayer.dataProvider().dataSourceUri().split('|')[0] # Load the assinged shape file layer into qgis, and show on the canvas. iface.addVectorLayer(source, QFileInfo(source).baseName(), 'ogr') pointLayer, lineLayer = pointAndLine(newPolygonLayer, projFolder) return newPolygonLayer, pointLayer, lineLayer
def get_dem_points(flowlines, dem, workspace): os.chdir(workspace) # sample the line and create a point layer sample_nodes = processing.runalg("qgis:extractnodes", str(os.path.join(workspace, flowlines)), None) n_nodes = sample_nodes['OUTPUT'] #iface.addVectorLayer(n_nodes, "n_nodes","ogr") # ensure that the points and raster are in the same coordinate system sample_nodes_reproj = processing.runalg("qgis:reprojectlayer", n_nodes, "EPSG:4269", None) reproj_n_nodes = sample_nodes_reproj['OUTPUT'] #iface.addVectorLayer(reproj_n_nodes, "reproj_n_nodes","ogr") # join the raster dem data to the sampled points rlayer = QgsRasterLayer(dem, u'OUTPUT') ext = rlayer.extent() xmin = ext.xMinimum() xmax = ext.xMaximum() ymin = ext.yMinimum() ymax = ext.yMaximum() coords = "%f,%f,%f,%f" % (xmin, xmax, ymin, ymax ) # this is a string that stores the coordinates dem_nodes = processing.runalg("grass7:v.sample", reproj_n_nodes, "COMID", dem, 1, 0, coords, -1, 0.0001, 0, None) dem_nodes_sampled = dem_nodes['output'] #iface.addVectorLayer(dem_nodes_sampled, "dem_nodes_sampled","ogr") dns_prj = processing.runalg("qgis:reprojectlayer", dem_nodes_sampled, "EPSG:4269", None) dns_reproj = dns_prj['OUTPUT'] #iface.addVectorLayer(dns_reproj, "dns_reproj","ogr") # intersect the sampled points with dem data with the polyline in order to obtain lineID's in the point attributes dem_nodes_lineID = processing.runalg("qgis:intersection", dns_reproj, os.path.join(workspace, flowlines), False, None) # export this file dem_nodes_dir = dem_nodes_lineID['OUTPUT'] iface.addVectorLayer(dem_nodes_dir, "sampled_points", "ogr") _vlayer = QgsMapLayerRegistry.instance().mapLayersByName( "sampled_points")[0] _writer = QgsVectorFileWriter.writeAsVectorFormat(_vlayer, os.path.join(workspace,"sampled_points.shp"), \ "utf-8", None, "ESRI Shapefile") print("Done.") return os.path.join(workspace, "sampled_points.shp")
def nodeCopy(node,newname=None,position=None,target_node=None): """ nodeMove: Moves 'node' in position or position 'position' in group 'target_node' :param node: Node to move or name of node to move :param target_node: Target group to move 'node' to or name of the target group :return: moved node or None if source or target node do not exist """ if oeq_global.isStringOrUnicode(node): node = nodeByName(node) if len(node) == 0: return None node = node[0] if target_node == None: target_node = node.parent() else: if oeq_global.isStringOrUnicode(target_node): target_node = nodeByName(target_node) if len(target_node) == 0: return None target_node = target_node[0] source_layer = node.layer() new_layer = iface.addVectorLayer(source_layer.source(), newname,source_layer.providerType()) #oeq_global.OeQ_wait_for_renderer(60000) new_node = nodeByLayer(new_layer)[0] new_node = nodeMove(new_node,position,target_node) QgsMapLayerRegistry.instance().addMapLayer(new_layer, False) #oeq_global.OeQ_wait_for_renderer(60000) #oeq_global.OeQ_unlockQgis() #oeq_global.OeQ_wait(0.1) return new_node
def isochrones(GEO_COM): geo = iface.addVectorLayer("GEO_COM","GEO","ogr") flag = 0 while flag != 1: flag = raw_input("Veuillez suivre le mode d'emploi pour créer une isochrone de 10 min à pieds, puis taper 1 et valider avec Entree.")
def loadFile(self, path, delimiter, column): """ Load csv file into qgis """ if not path.startswith('/'): path = '/' + path output_file_uri = 'file://{}?delimiter={}&crs=EPSG:4326&wktField={}'.\ format( path, delimiter, column ) vlayer = QgsVectorLayer(output_file_uri, 'Output file', 'delimitedtext') iface.addVectorLayer(output_file_uri, 'Output Layer', 'delimitedtext') iface.mapCanvas().refresh()
def write_temporary_vector_layer_to_disk(vlayer, style=None, replace_in_legend=True): import os from qgis.utils import iface from mole import oeq_global if oeq_global.OeQ_project_name() == '': iface.actionSaveProjectAs().trigger() layer_name = vlayer.name() layer_crs = vlayer.crs() path = os.path.join(oeq_global.OeQ_project_path(), layer_name + '.shp') error = QgsVectorFileWriter.writeAsVectorFormat(vlayer, path, "System", layer_crs, 'ESRI Shapefile') if error == QgsVectorFileWriter.NoError: if replace_in_legend: QgsMapLayerRegistry.instance().removeMapLayer(vlayer.id()) rewritten_layer = iface.addVectorLayer(path, layer_name, "ogr") #oeq_global.OeQ_wait_for_renderer(60000) if not rewritten_layer.isValid(): oeq_global.OeQ_push_warning(title='Write Error!', message='path') return vlayer if style != None: add_style_to_layer(style, rewritten_layer) rewritten_layer.startEditing() time.sleep(0.2) rewritten_layer.commitChanges() return rewritten_layer else: oeq_global.OeQ_push_warning(title='Write Error!', message='path') return vlayer
def import_shp(path, geometry): """Loads the shapefile depending on the desired geometry (lines or points) Parameters ---------- path : str path to shapefile folder geomtry:str desired geometry (lines or points) Returns ------- osgeo.org.DataSource opened shapefile with ogr """ if (geometry not in ("points", "lines")): print("Geometry input not valid") else: geometry_file = geometry + ".shp" print('### Opening %s ###' % geometry_file) shape_file = os.path.join(path, geometry_file) layerShp = iface.addVectorLayer(shape_file, "shape:", "ogr") if not layerShp: print("Shapefile failed to load!") else: return (layerShp)
def nodeVectorSave(node,filepath=None,crs=None,load=False): from qgis.core import QgsCoordinateReferenceSystem,QgsVectorFileWriter from qgis.utils import iface from mole import oeq_global if oeq_global.isStringOrUnicode(node): node = nodeByName(node) if not node: return None node = node[0] if not filepath: filepath=node.layer().source() if not crs: crs=node.layer().crs() else: crs = QgsCoordinateReferenceSystem(int(crs.split(':')[1]), QgsCoordinateReferenceSystem.EpsgCrsId) QgsVectorFileWriter.writeAsVectorFormat( node.layer(),filepath,'System',crs,'ESRI Shapefile') if load: iface.addVectorLayer(filepath,None, 'ogr')
def add_shp_to_iface(self): basename = "" provider = "ogr" from qgis.utils import iface layer = iface.addVectorLayer(self.shape_path, basename, provider) if not layer: logger.error("Layer %s failed to load!", self.shape_path)
def clip_the_raster(raster, vector, workspace): os.chdir(workspace) # need to project the county to the same projection system as the raster reproj_county = processing.runalg("qgis:reprojectlayer", \ str(os.path.join(workspace, vector)), \ "EPSG:4326", None) reproj = reproj_county['OUTPUT'] iface.addVectorLayer(reproj, "reproj_county","ogr") print "Projection Complete..." clipped_raster = processing.runalg("saga:clipgridwithpolygon", str(os.path.join(workspace, raster)), \ str(reproj), \ None) print("Done.") return reproj, clipped_raster
def createShape(shapeName, EPSG): #shapeName = "U:/StereoPhoto/ShapeFile/TestLayer.shp" fields = QgsFields() fields.append(QgsField("id", QVariant.Int)) feature = QgsFeature() vectorWriter = QgsVectorFileWriter(shapeName, "System", fields, QgsWkbTypes.MultiPolygon, QgsCoordinateReferenceSystem(EPSG), "ESRI Shapefile") vectorWriter.addFeature(feature) del vectorWriter vectorLayer = iface.addVectorLayer(shapeName, "", "ogr") return vectorLayer
def CreateVritualDebLayer(self): # Vraag naar map met Deborah bestanden folder = str( QFileDialog.getExistingDirectory( None, "Selecteer Deborah Projectmap", "D:\\Google Drive\\Dev\\QGis Probeersels\\TZD78")) if not folder: return # Controleer of bestanden bestaan project = folder.split('\\')[-1] kop_path = os.path.join(folder, project + "_kop.dbf") laag_path = os.path.join(folder, project + "_laag.dbf") if not (os.path.isfile(kop_path) and os.path.isfile(laag_path)): iface.messageBar().pushMessage( "Fout", "Kan geen kop en/of laaggegevens vinden in de opgegeven map", level=QgsMessageBar.CRITICAL) return # Maak virtuele laag aan filecontent = getVRTText(self, project) filepath = os.path.join(folder, project + "_boringen.vrt") outputfile = open(filepath, "w") outputfile.write(filecontent) outputfile.close() # Voeg de virtuele laag toe aan de legenda layer = iface.addVectorLayer(filepath, project + "_boringen", "ogr") if not layer: QgsMessageLog.instance().logMessage('Kon virtuele laag niet laden!', level=QgsMessageLog.WARNING) # Voeg ook de laaggegevens toe aan de legenda voor evt. queries filepath = os.path.join(folder, project + "_laag.dbf") layer = iface.addVectorLayer(filepath, project + "_lagen", "ogr") if not layer: QgsMessageLog.instance().logMessage('Kon laaggegevens niet laden!', level=QgsMessageLog.WARNING) iface.mapCanvas().setExtent(layer.extent())
def load_file(self): if self.first_start == True: self.first_start = False """Method that opens the browse window to select file""" #Open the file browser window filename1 = QFileDialog.getOpenFileName( filter="*.shp") #Get the first value of the turple and convert to string getpath = "{}".format(filename1[0]) #Load map vlayer = iface.addVectorLayer(getpath, "Shapefile", "ogr")
def nodeConvertCRS(node,crs=None): import os, subprocess os.environ['PATH'] += ":"+"/usr/local/bin" from mole import oeq_global from mole.qgisinteraction import layer_interaction if crs == None: crs='epsg:4326' #default is WGS84 if oeq_global.isStringOrUnicode(node): node = nodeByName(node) if len(node) == 0: return None node = node[0] src_crs = node.layer().crs().authid() name=node.layer().name() src_path = node.layer().source() src_dir =os.path.dirname(src_path) src_name = os.path.basename(src_path).split('.')[0] src_ext = src_path.split('.')[1] tgt_name = src_name+'_tmp' tgt_path = os.path.join(src_dir,tgt_name+'.'+src_ext) bu_name= src_name+'_'+src_crs.split(':')[1] bu_path = os.path.join(src_dir,bu_name+'.'+src_ext) nodeVectorSave(node,tgt_path,crs) oeq_global.OeQ_wait_for_file(tgt_path) nodeRemove(node) # return None layer_interaction.remove_filegroup(src_dir,bu_name,ignore=['qml']) layer_interaction.rename_filegroup(src_dir,src_name,bu_name,ignore=['qml']) oeq_global.OeQ_wait_for_file(bu_name) layer_interaction.rename_filegroup(src_dir,tgt_name,src_name,ignore=['qml']) oeq_global.OeQ_wait_for_file(src_path) iface.addVectorLayer(src_path,name, 'ogr') oeq_global.OeQ_wait_for_renderer() newnode=nodeByName(name) if newnode: newnode[0].layer().triggerRepaint() #oeq_global.OeQ_wait_for_renderer(60000) return newnode[0] return None
def onSaveButton(self): print "Save button clicked" self.levelsUpdate() print self.levels raster = self.raster_box.currentLayer().dataProvider().dataSourceUri() rc = isolines.RadiationIsolines(raster) output_dir = os.path.dirname(raster) output_filename = '{}_isolines.shp'.format( os.path.splitext(os.path.basename(raster))[0]) output = os.path.join(output_dir, output_filename) rc.destination() rc.generate(self.levels) # print('{} generated'.format(output)) rg = generalizer.RadiationGeneralizer() # polygonization rp = polygonizer.RadiationPolygonizer(rc, self.saveReportName, rg) if self.check_shp.isChecked(): output_filename = '{}_polygons.shp'.format( os.path.splitext(os.path.basename(raster))[0]) output = os.path.join(output_dir, output_filename) # remove layer with same name as newly created layer for lyr in QgsMapLayerRegistry.instance().mapLayers().values(): if lyr.source() == output: QgsMapLayerRegistry.instance().removeMapLayer(lyr.id()) # remove shape file with same name if os.path.isfile(output): os.remove(output) if os.path.isfile(output.split('.')[0] + '.shx'): os.remove(output.split('.')[0] + '.shx') if os.path.isfile(output.split('.')[0] + '.dbf'): os.remove(output.split('.')[0] + '.dbf') if os.path.isfile(output.split('.')[0] + '.prj'): os.remove(output.split('.')[0] + '.prj') rp.destination(str(output)) index = self.type_box.currentIndex() rp.polygonize(index) print('{} generated'.format(output)) newLayer = iface.addVectorLayer( u'{f}'.format(f=output), u'{f}'.format(f=QFileInfo(output).baseName()), "ogr") else: rp.destination() index = self.type_box.currentIndex() rp.polygonize(index)
def loadDomain(self, domainTableName, domainGroup): """ Loads layer domains :param domainTableName: :param domainGroup: :return: """ #TODO: Avaliar se o table = deve ser diferente uri = "dbname='%s' host=%s port=%s user='******' password='******' key=code table=\"dominios\".\"%s\" sql=" % (self.database, self.host, self.port, self.user, self.password, domainTableName) domLayer = iface.addVectorLayer(uri, domainTableName, self.provider) self.iface.legendInterface().moveLayer(domLayer, domainGroup) return domLayer
def loadLayer(self, inputParam, idSubgrupo, loadedLayers, useInheritance, useQml, uniqueLoad, stylePath, domainDict, multiColumnsDict, domLayerDict, edgvVersion, geomColumn = None, isView = False): """ Loads a layer :param lyrName: Layer nmae :param loadedLayers: list of loaded layers :param idSubgrupo: sub group id :param uniqueLoad: boolean to mark if the layer should only be loaded once :param stylePath: path to the styles used :param domLayerDict: domain dictionary :return: """ if isinstance(inputParam,dict): lyrName = inputParam['lyrName'] schema = inputParam['tableSchema'] geomColumn = inputParam['geom'] tableName = inputParam['tableName'] srid = self.geomDict['tablePerspective'][tableName]['srid'] else: lyrName = inputParam tableName = self.geomDict['tablePerspective'][lyrName]['tableName'] schema = self.geomDict['tablePerspective'][lyrName]['schema'] geomColumn = self.geomDict['tablePerspective'][lyrName]['geometryColumn'] srid = self.geomDict['tablePerspective'][lyrName]['srid'] if uniqueLoad: lyr = self.checkLoaded(tableName, loadedLayers) if lyr: return lyr fullName = '''"{0}"."{1}"'''.format(schema, tableName) pkColumn = self.abstractDb.getPrimaryKeyColumn(fullName) if useInheritance or self.abstractDb.getDatabaseVersion() in ['3.0', 'Non_Edgv']: sql = '' else: sql = self.abstractDb.gen.loadLayerFromDatabase(fullName, pkColumn=pkColumn) self.setDataSource(schema, tableName, geomColumn, sql, pkColumn=pkColumn) vlayer = iface.addVectorLayer(self.uri.uri(), tableName, self.provider) crs = QgsCoordinateReferenceSystem(int(srid), QgsCoordinateReferenceSystem.EpsgCrsId) if vlayer: vlayer.setCrs(crs) if useQml: vlayer = self.setDomainsAndRestrictionsWithQml(vlayer) else: vlayer = self.setDomainsAndRestrictions(vlayer, tableName, domainDict, multiColumnsDict, domLayerDict) if stylePath: fullPath = self.getStyle(stylePath, tableName) if fullPath: vlayer.applyNamedStyle(fullPath) iface.legendInterface().moveLayer(vlayer, idSubgrupo) if not vlayer.isValid(): QgsMessageLog.logMessage(vlayer.error().summary(), "DSG Tools Plugin", QgsMessageLog.CRITICAL) vlayer = self.createMeasureColumn(vlayer) return vlayer
def nodeSaveMemoryLayer(node , path=None , providertype="ESRI Shapefile"): if oeq_global.isStringOrUnicode(node): node = nodeByName(node) if len(node) == 0: return None new_layer = node[0].layer() new_layer_name = new_layer.name() writer = QgsVectorFileWriter.writeAsVectorFormat(new_layer, os.path.join(path , new_layer_name+'.shp'), "System", new_layer.crs(), providertype) if writer != QgsVectorFileWriter.NoError: oeq_global.OeQ_push_error(title='Write Error:', message=os.path.join(path , new_layer_name+'.shp')) return None del writer oeq_global.OeQ_wait_for_file(os.path.join(path , new_layer_name+'.shp')) iface.addVectorLayer(os.path.join(path , new_layer_name+'.shp'),new_layer_name, 'ogr') #oeq_global.OeQ_wait_for_renderer(60000) target_node = node.parent() position = nodePosition(node,target_node) new_node = nodeMove(new_layer_name,position,target_node) #oeq_global.OeQ_unlockQgis() return new_node
def loadScenario(self): """displays open file dialog to select bus track input file""" gpkgPath, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Select Scenario GeoPackage", "", "GeoPackage (*.gpkg)") self.workingFolder = os.path.dirname(gpkgPath) self.currentGpkg = gpkgPath if gpkgPath: """ delete all layers in project""" self.cleanAllLayers() """ open the GeoPackage layers""" uri = absolutePath(gpkgPath +"|layername=demand") layer = iface.addVectorLayer(uri, "Demand", "ogr") uri = absolutePath(gpkgPath +"|layername=VehicleTypes") layer = iface.addVectorLayer(uri, "VehicleTypes", "ogr") uri = absolutePath(gpkgPath +"|layername=RoadTypes") layer = iface.addVectorLayer(uri, "RoadTypes", "ogr") uri = absolutePath(gpkgPath +"|layername=Periods") layer = iface.addVectorLayer(uri, "Periods", "ogr") uri = absolutePath(gpkgPath +"|layername=Noeuds") layer = iface.addVectorLayer(uri, "Noeuds", "ogr") uri = absolutePath(gpkgPath +"|layername=Liens") layer = iface.addVectorLayer(uri, "Liens", "ogr") uri = absolutePath(gpkgPath +"|layername=Feux") layer = iface.addVectorLayer(uri, "Feux", "ogr") uri = absolutePath(gpkgPath +"|layername=General") layer = iface.addVectorLayer(uri, "General", "ogr") uri = absolutePath(gpkgPath +"|layername=Regulations") from qgis.core import QgsVectorLayer test = QgsVectorLayer(uri, "Regulations", "ogr") if not test.isValid(): print("No regulations layer for the moment, maybe you should add one...") else: layer = iface.addVectorLayer(uri, "Regulations", "ogr") self.applyBasicStyle()
def __add_spatialite_layer_to_qgis(self): """ Add SpatiaLite layer to the current QGIS project. """ uri = QgsDataSourceUri() uri.setDatabase(self.__output_filename) schema = '' geom_column = 'Geometry' uri.setDataSource(schema, self.__table_name, geom_column) display_name = 'Addresses' vlayer = iface.addVectorLayer(uri.uri(), display_name, 'spatialite') if not vlayer: iface.messageBar().pushCritical( "Eroare încărcare strat", "A apărut o eroare la încărcarea stratului SpatiaLite")
def loadDomain(self, domainTableName, domainGroup): """ Loads layer domains :param domainTableName: :param domainGroup: :return: """ #TODO: Avaliar se o table = deve ser diferente uri = "dbname='%s' host=%s port=%s user='******' password='******' key=code table=\"dominios\".\"%s\" sql=" % ( self.database, self.host, self.port, self.user, self.password, domainTableName) domLayer = iface.addVectorLayer(uri, domainTableName, self.provider) self.iface.legendInterface().moveLayer(domLayer, domainGroup) return domLayer
def nodeCreateVectorLayer(nodename, position='bottom',target_node=None,path=None,source="Point",crs=None,providertype="ESRI Shapefile",indexfieldname='id'): if target_node == None: target_node = QgsProject.instance().layerTreeRoot() else: if oeq_global.isStringOrUnicode(target_node): target_node = nodeByName(target_node) if len(target_node) == 0: return None target_node = target_node[0] if path == None: path= oeq_global.OeQ_project_path() if crs == None: crs = config.project_crs new_layer = QgsVectorLayer(source + '?crs=' + crs, nodename, "memory") new_layer.setProviderEncoding('System') #test dataprovider = new_layer.dataProvider() dataprovider.addAttributes([QgsField(indexfieldname, QVariant.Int)]) new_layer.updateFields() writer = QgsVectorFileWriter.writeAsVectorFormat(new_layer, os.path.join(path , nodename+'.shp'), "System", new_layer.crs(), providertype) if writer != QgsVectorFileWriter.NoError: oeq_global.OeQ_push_error(title='Write Error:', message=os.path.join(path , nodename+'.shp')) return None del writer oeq_global.OeQ_wait_for_file(os.path.join(path , nodename+'.shp')) iface.addVectorLayer(os.path.join(path , nodename+'.shp'),nodename, 'ogr') #oeq_global.OeQ_wait_for_renderer(60000) new_node = nodeMove(nodename,position,target_node) new_layer = new_node.layer() #dataprovider = new_layer.dataProvider() #dataprovider.addAttributes([QgsField(indexfieldname, QVariant.Int)]) #new_layer.updateFields() #oeq_global.OeQ_unlockQgis() return new_node
def loadDomain(self, domainTableName, domainGroup): """ Loads layer domains :param domainTableName: :param domainGroup: :return: """ #TODO: Avaliar se o table = deve ser diferente uri = QgsDataSourceURI() uri.setDatabase(self.abstractDb.db.databaseName()) uri.setDataSource('', 'dominios_'+domainTableName, None) #TODO Load domain layer into a group domLayer = iface.addVectorLayer(uri.uri(), domainTableName, self.provider) self.iface.legendInterface().moveLayer(domLayer, domainGroup) return domLayer
def loadLayer(self, inputParam, loadedLayers, idSubgrupo, uniqueLoad, stylePath, domLayerDict): """ Loads a layer :param lyrName: Layer nmae :param loadedLayers: list of loaded layers :param idSubgrupo: sub group id :param uniqueLoad: boolean to mark if the layer should only be loaded once :param stylePath: path to the styles used :param domLayerDict: domain dictionary :return: """ if isinstance(inputParam, dict): lyrName = inputParam['lyrName'] schema = inputParam['tableSchema'] geomColumn = inputParam['geom'] tableName = inputParam['tableName'] srid = self.geomDict['tablePerspective'][tableName]['srid'] else: lyrName = inputParam tableName = self.geomDict['tablePerspective'][lyrName]['tableName'] schema = self.geomDict['tablePerspective'][lyrName]['schema'] geomColumn = self.geomDict['tablePerspective'][lyrName][ 'geometryColumn'] srid = self.geomDict['tablePerspective'][lyrName]['srid'] if uniqueLoad: lyr = self.checkLoaded(lyrName, loadedLayers) if lyr: return lyr self.setDataSource('', '_'.join([schema, tableName]), geomColumn, '') vlayer = iface.addVectorLayer(self.uri.uri(), tableName, self.provider) crs = QgsCoordinateReferenceSystem( int(srid), QgsCoordinateReferenceSystem.EpsgCrsId) vlayer.setCrs(crs) vlayer = self.setDomainsAndRestrictionsWithQml(vlayer) vlayer = self.setMulti(vlayer, domLayerDict) if stylePath: fullPath = self.getStyle(stylePath, tableName) if fullPath: vlayer.applyNamedStyle(fullPath) iface.legendInterface().moveLayer(vlayer, idSubgrupo) if not vlayer.isValid(): QgsMessageLog.logMessage(vlayer.error().summary(), "DSG Tools Plugin", QgsMessageLog.CRITICAL) vlayer = self.createMeasureColumn(vlayer) return vlayer
def loadDomain(self, domainTableName, domainGroup): """ Loads layer domains :param domainTableName: :param domainGroup: :return: """ #TODO: Avaliar se o table = deve ser diferente uri = QgsDataSourceUri() uri.setDatabase(self.abstractDb.db.databaseName()) uri.setDataSource('', 'dominios_' + domainTableName, None) #TODO Load domain layer into a group domLayer = iface.addVectorLayer(uri.uri(), domainTableName, self.provider) self.iface.legendInterface().moveLayer(domLayer, domainGroup) return domLayer
def _open_csv(self, full_path): # Add new HTTPConnection like in source # https://github.com/qgis/QGIS/blob/master/src/gui/qgsnewhttpconnection.cpp self.msg_log_debug(u'add CSV file: {0}'.format(full_path)) name = os.path.basename(full_path) # create new dialog csv_dlg = QgsProviderRegistry.instance().createSelectionWidget( "delimitedtext", self.main_win) csv_dlg.addVectorLayer.connect( lambda url: iface.addVectorLayer(url, name, "delimitedtext")) csv_dlg.children()[1].children()[2].setFilePath(full_path) csv_dlg.show()
def add_layer_as_reprojected_gpkg(project_folder, geo_layer_folder, source_file, target_crs, identifier, layer_name=''): path = project_folder + geo_layer_folder layer = QgsVectorLayer(path + source_file, '', 'ogr') QgsVectorFileWriter.writeAsVectorFormat( layer, '{}{}.gpkg'.format(path, identifier), 'utf-8', QgsCoordinateReferenceSystem(target_crs), 'GPKG') return iface.addVectorLayer('{}{}.gpkg'.format(path, identifier), layer_name, 'ogr')
def LagShape(filnavn, filter, nyeVektorlag, selectedLayer ): # Danner nye vektorlag basert på gruppene valgt i analysen if os.path.isfile(nyeVektorlag.text() + filnavn + '.shp'): os.remove( nyeVektorlag.text() + filnavn + '.shp' ) # Hvis ett vektolag med samme navn allerede finnes, fjern denne filen selectedLayer.selectByExpression( filter ) # Velger delere av ledningsnettverket basert på filter som er blitt valgt i analysen fn = nyeVektorlag.text( ) + filnavn + '.shp' # Lager en ny shape fil av det valgte delen writer = QgsVectorFileWriter.writeAsVectorFormat(selectedLayer, fn, 'utf-8', \ driverName='ESRI Shapefile', onlySelected=True) # Skriver den nye shape filen som vektorformat selected_layer = iface.addVectorLayer( fn, '', 'ogr') # Legger det nye vektorlaget inn som ett aktivt vektorlag
def importResults(self, epsg): # if self.computeThread.aborted: # return # Import results to QGIS temp_path = self.computeThread.output_path() for file in os.listdir(temp_path): if file.endswith(".tif"): try: self._se_layer = iface.addRasterLayer(os.path.join(temp_path, file), self.tr('G Faktor')) crs = self._se_layer.crs() crs.createFromId(epsg) self._se_layer.setCrs(crs) self.layerOnTop(self._se_layer) # # Set style be renderer: # self.setStyle(self._se_layer) # # set style on .gml file: euc = self.shp_box_euc.currentLayer() self._euc_vector = iface.addVectorLayer(euc.source(), "EUC", euc.providerType()) self.layerOnTop(self._euc_vector) se_source = self._se_layer.source() self.zonalStat(self._euc_vector, se_source) self.setVectorErosionStyle(self._euc_vector) self._euc_vector.commitChanges() # for field in _euc_vector.pendingFields(): # if field.name() == 'C': # _euc_vector.startEditing() # oldname = field.name() # field.setName('NewName') # newname = field.name() # self.showError(u'Old name: {},New name: {}'.format(oldname,newname)) # except: self.showError(u'Error during compute zonal statistics.') self._first_computation = False self.computeThread.cleanup() del self.computeThread # kill progress bar if it is still on (if computation is still on) try: self.progress.setParent(None) self.iface.messageBar().popWidget(self.progressMessageBar) except: pass
def loadLayer(self, inputParam, loadedLayers, idSubgrupo, uniqueLoad, stylePath, domLayerDict): """ Loads a layer :param lyrName: Layer nmae :param loadedLayers: list of loaded layers :param idSubgrupo: sub group id :param uniqueLoad: boolean to mark if the layer should only be loaded once :param stylePath: path to the styles used :param domLayerDict: domain dictionary :return: """ if isinstance(inputParam,dict): lyrName = inputParam['lyrName'] schema = inputParam['tableSchema'] geomColumn = inputParam['geom'] tableName = inputParam['tableName'] srid = self.geomDict['tablePerspective'][tableName]['srid'] else: lyrName = inputParam tableName = self.geomDict['tablePerspective'][lyrName]['tableName'] schema = self.geomDict['tablePerspective'][lyrName]['schema'] geomColumn = self.geomDict['tablePerspective'][lyrName]['geometryColumn'] srid = self.geomDict['tablePerspective'][lyrName]['srid'] if uniqueLoad: lyr = self.checkLoaded(lyrName, loadedLayers) if lyr: return lyr self.setDataSource('', '_'.join([schema,tableName]), geomColumn, '') vlayer = iface.addVectorLayer(self.uri.uri(), tableName, self.provider) crs = QgsCoordinateReferenceSystem(int(srid), QgsCoordinateReferenceSystem.EpsgCrsId) vlayer.setCrs(crs) vlayer = self.setDomainsAndRestrictionsWithQml(vlayer) vlayer = self.setMulti(vlayer,domLayerDict) if stylePath: fullPath = self.getStyle(stylePath, tableName) if fullPath: vlayer.applyNamedStyle(fullPath) iface.legendInterface().moveLayer(vlayer, idSubgrupo) if not vlayer.isValid(): QgsMessageLog.logMessage(vlayer.error().summary(), "DSG Tools Plugin", QgsMessageLog.CRITICAL) vlayer = self.createMeasureColumn(vlayer) return vlayer
def addNewLayer(self): """End computeThread. Ask to add new layer of computed points to map canvas. """ # Message box reply = QMessageBox.question( self, u'Ground Radiation Monitoring', u"Add new layer to map canvas?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.Yes) # add map layer to map canvas if reply == QMessageBox.Yes: newLayer = iface.addVectorLayer( u'{f}'.format(f=self.saveShpNameOriginal), u'{f}'.format( f=QFileInfo(self.saveShpNameOriginal).baseName()), "ogr") self.iface.messageBar().popWidget(self.progressMessageBar) self.save_button.setEnabled(True)
def createShp(self, out_shp, features, inLayer, sr, out_type=None): self.new_name = inLayer.name() + "_new" self.geomType = QgsWkbTypes.displayString(inLayer.wkbType()) if out_type == "m": self.new_shp = QgsVectorLayer(self.geomType, self.new_name, "memory") self.pr = self.new_shp.dataProvider() self.fields = [ QgsField(n, t) for t, n, _ in features[0]["properties"] ] self.pr.addAttributes(self.fields) self.new_shp.updateFields() for f in features: self.feat = QgsFeature() self.feat.setGeometry(f["geometry"]) self.attr = [k for i, j, k in f["properties"]] self.feat.setAttributes(self.attr) self.pr.addFeature(self.feat) self.new_shp.updateExtents() QgsProject.instance().addMapLayer(self.new_shp) self.new_shp.setCrs(QgsCoordinateReferenceSystem.fromWkt(sr)) else: self.fields = QgsFields() for t, n, _ in features[0]["properties"]: self.fields.append(QgsField(n, t)) self.writer = QgsVectorFileWriter( out_shp, 'UTF-8', self.fields, inLayer.wkbType(), QgsCoordinateReferenceSystem.fromWkt(sr), 'ESRI Shapefile') for f in features: self.feat = QgsFeature() self.feat.setGeometry(f["geometry"]) self.attr = [k for i, j, k in f["properties"]] self.feat.setAttributes(self.attr) self.writer.addFeature(self.feat) self.layer = iface.addVectorLayer(out_shp, '', 'ogr') self.layer.setExtent(inLayer.extent()) del (self.writer)
def loadLayer(data_source, layer_name, provider): ''' To get data_source : open the layer, get in properties and copy past the source. Exemple : data_source = ur"""dbname='D:/inondation.sqlite' table="commune" (geometry) sql=""" data_source = ur"""\\10.27.8.61\gb_cons\DONNEE_GENERIQUE\N_INTERCOMMUNALITE\L_EPCI_BDP_S_027.shp""" ''' try: canvas = iface.mapCanvas() canvas.setRenderFlag(False) layer = iface.addVectorLayer(data_source, layer_name, provider) ev_loop = QEventLoop() canvas.renderComplete.connect(ev_loop.quit) canvas.setRenderFlag(True) ev_loop.exec_() return layer except: return False
def newScenario(self): ###### Get path to file gpkgPath , _ = QtWidgets.QFileDialog.getSaveFileName(self, "Save new GeoPackage as", "", "GeoPackage (*.gpkg)") self.workingFolder = os.path.dirname(gpkgPath) # ######FILE MANAGEMENT old_name = absolutePath('baseQstream/base.gpkg') shutil.copy(old_name, gpkgPath) # clean layers self.cleanAllLayers() ####### Open the layers and add them to the workspace uri = absolutePath(gpkgPath +"|layername=demand") layer = iface.addVectorLayer(uri, "Demand", "ogr") uri = absolutePath(gpkgPath +"|layername=VehicleTypes") layer = iface.addVectorLayer(uri, "VehicleTypes", "ogr") uri = absolutePath(gpkgPath +"|layername=RoadTypes") layer = iface.addVectorLayer(uri, "RoadTypes", "ogr") uri = absolutePath(gpkgPath +"|layername=Periods") layer = iface.addVectorLayer(uri, "Periods", "ogr") uri = absolutePath(gpkgPath +"|layername=Noeuds") layer = iface.addVectorLayer(uri, "Noeuds", "ogr") uri = absolutePath(gpkgPath +"|layername=Liens") layer = iface.addVectorLayer(uri, "Liens", "ogr") uri = absolutePath(gpkgPath +"|layername=Feux") layer = iface.addVectorLayer(uri, "Feux", "ogr") uri = absolutePath(gpkgPath +"|layername=General") layer = iface.addVectorLayer(uri, "General", "ogr") ####### Apply basic style self.applyBasicStyle()
def getLayers(self): text = self.layersText.toPlainText() names = text.split("\n") crs = self.crsText.toPlainText() for name in names: subprocess.run([ "scp", "acald013@hn:/tmp/edges{}.wkt".format(name), "/home/and/tmp/edges/edges{}.wkt".format(name) ]) instance = QgsProject.instance() for name in names: layers = instance.mapLayersByName(name) for layer in layers: instance.removeMapLayer(layer) iface.mapCanvas().refresh() for name in names: uri = "file:///home/and/tmp/edges/edges{}.wkt?delimiter={}&useHeader=no&crs=epsg:{}&wktField={}".format( name, "\\t", crs, "field_1") layer = iface.addVectorLayer(uri, name, "delimitedtext") if name == "Cells": symbol = QgsFillSymbol.createSimple({ 'color_border': 'blue', 'style': 'no', 'style_border': 'dash' }) layer.renderer().setSymbol(symbol) layer.triggerRepaint() if name == "Faces": symbol = QgsFillSymbol.createSimple({'color': 'green'}) layer.renderer().setSymbol(symbol) pal_layer = QgsPalLayerSettings() pal_layer.fieldName = 'field_2' pal_layer.enabled = True pal_layer.placement = QgsPalLayerSettings.Free labels = QgsVectorLayerSimpleLabeling(pal_layer) layer.setLabeling(labels) layer.setLabelsEnabled(True) layer.triggerRepaint() with open(os.path.join(os.path.dirname(__file__), 'history.txt'), 'w') as f: f.write("{}\n{}".format(text, crs))
def load_layers(self, type): answer = QMessageBox.No while (answer == QMessageBox.No): self.information( "File Select", "Select your " + type + " layer from a Geopackage") input = self.fileDialog("File Select")[0] while (input[-5:] != ".gpkg"): self.information("Invalid Geopackage", "That is not a .gpkg file! Please reselect!") input = self.fileDialog("File Select")[0] answer = self.question("Confirmation", "Is " + input + " the correct file?") if answer == QMessageBox.Yes: inputAnswer = self.inputDialog(1, "Layer Name", "Name your layer: ") layer = iface.addVectorLayer(input, "", "ogr") if ((inputAnswer[1]) == True): layer.setName(inputAnswer[0]) break self.information("Reselect", "Please select the correct " + type + " file!")
def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. filename = os.path.abspath("Sample_Data/sample_data.shp") iface.messageBar().pushMessage("Shapefile loaded ...", QgsMessageBar.INFO) source_layer = iface.addVectorLayer(filename, "sample_data", "ogr") centroid = QgsVectorLayer('Point', 'Centroid', 'memory') fields = QgsFields() fields.append(QgsField("code", QVariant.String)) fields.append(QgsField("x", QVariant.Double)) fields.append(QgsField("y", QVariant.Double)) # Define additional attributes already on the layer level centroid_layer = QgsVectorFileWriter( centroid, "UTF8", fields, QGis.WKBPoint, QgsCoordinateReferenceSystem(4326), "ESRI Shapefile") if centroid_layer.hasError() != QgsVectorFileWriter.NoError: print("Error when creating centroid: ", centroid_layer.errorMessage()) iface.messageBar().pushMessage("Feature addition failed.", QgsMessageBar.CRITICAL) centroid_layer.startEditing() # Loop over all features for source_feature in source_layer.getFeatures(): geometry = source_feature.geometry() centroid = geometry.centroid().asPoint() pts = [Centroid] name = source_feature["code"] # Create the new feature with the fields of the ogr layer # And set geometry and attribute before adding it to the target layer centroid_feature = QgsFeature(source_layer.fields()) centroid_feature = source_feature.attributes() centroid_feature.setAttributes(centroid_feature) centroid_feature.setGeometry(centroid) centroid_feature['code'] = name centroid_layer.addFeature(centroid_feature) # Loop centroids to shapefile for x, y in pts: centroid_feature = QgsFeature() point = QgsPoint(x, y) centroid_feature.setGeometry(QgsGeometry.fromPoint(point)) centroid_feature.setAttributes(attrs) prov.addFeatures([centroid_feature]) centroid_layer.commitChanges() # Add the layer to the registry QgsMapLayerRegistry.instance().addMapLayer(centroid_layer) # Save centroid layer as csv format QgsVectorFileWriter.writeAsVectorFormat( centroid_layer, r'extract_centroid', "utf-8", None, "CSV", layerOptions='GEOMETRY=AS_XYZ') iface.messageBar().pushMessage("Extract centroid saved as csv ...", QgsMessageBar.INFO)
""" ##[GEEPS]=group ##Load Shapefile Layers from Folder=name ##Shapefile_Folder=folder ##Root_Folder_Only=boolean True ##output=output number import os, fnmatch from qgis.core import * from qgis.utils import iface from processing.tools.vector import VectorWriter # function def find_files(directory, pattern, only_root_directory): for root, dirs, files in os.walk(directory): for basename in files: if fnmatch.fnmatch(basename.lower(), pattern): filename = os.path.join(root, basename) yield filename if (only_root_directory): break # main count = 0 for src_file in find_files(Shapefile_Folder, '*.shp', Root_Folder_Only): (head, tail) = os.path.split(src_file) (name, ext) = os.path.splitext(tail) vlayer = iface.addVectorLayer(src_file, name, "ogr") count += 1 output = count
def run(self): """Run method that performs all the real work""" # populate the Combo Box with the layers loaded in QGIS (used as clip layer) self.dlg.comboBox.clear() layers = self.iface.legendInterface().layers() layer_list = [] for layer in layers: layer_list.append(layer.name()) self.dlg.comboBox.addItems(layer_list) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: path = self.dlg.lineEdit.text() ### test, zda je validní cesta k adresáři if not os.path.isdir(path): iface.messageBar().pushMessage(u"Error", u"{} is not valid directory".format(path), level=QgsMessageBar.CRITICAL, duration=5) return ### test, zda cesta nekonci na lomitko (ci zpetne lomitko) if path.endswith('/') or path.endswith('\\') : path = path[0:len(path)-1] clip_path = path + "_clipped" try: if not os.path.exists(clip_path): os.makedirs(clip_path) except IOError as e: iface.messageBar().pushMessage(u"Error", u"{}".format(e), level=QgsMessageBar.CRITICAL, duration=5) return clip_name = self.dlg.comboBox.currentText() clip_layer = self.getVectorLayerByName(clip_name) try: files = [f for f in listdir(path) if isfile(join(path, f))] except IOError as e: iface.messageBar().pushMessage(u"Error", u"{}".format(e), level=QgsMessageBar.CRITICAL, duration=5) return files_shp = [] for file_item in files: extension = os.path.splitext(file_item) if extension[1] == ".shp": absolute_path = os.path.join(path, file_item) files_shp.append(absolute_path) layers = [] for path in files_shp: file_name = os.path.basename(path) name = os.path.splitext(file_name) layer = QgsVectorLayer(path, "name", "ogr") layers.append(layer) output_file = os.path.join(clip_path, name[0]) + "_clip.shp" processing.runalg("qgis:clip", layer, clip_layer, output_file) if self.dlg.checkBox.isChecked(): file_qgis_name = os.path.basename(output_file) qgis_name = os.path.splitext(file_qgis_name) iface.addVectorLayer(output_file, qgis_name[0], "ogr")
def success(self, path, base_name, provider_key): iface.addVectorLayer(path, base_name, provider_key) self.signalStatus.emit(3, tr('Successful import'))
def nodeConvertCRSold(node,crs=None): import os, subprocess os.environ['PATH'] += ":"+"/usr/local/bin" from mole import oeq_global from mole.qgisinteraction import layer_interaction if crs == None: crs='epsg:4326' #default is WGS84 if oeq_global.isStringOrUnicode(node): node = nodeByName(node) if len(node) == 0: return None node = node[0] src_crs = node.layer().crs().authid() name=node.layer().name() src_path = node.layer().source() src_dir =os.path.dirname(src_path) src_name = os.path.basename(src_path).split('.')[0] src_ext = src_path.split('.')[1] tgt_name = src_name+'_tmp' tgt_path = os.path.join(src_dir,tgt_name+'.'+src_ext) tgt_crs=QgsCoordinateReferenceSystem(int(crs.split(':')[1]), QgsCoordinateReferenceSystem.EpsgCrsId) bu_name= src_name+'_'+src_crs.split(':')[1] bu_path = os.path.join(src_dir,bu_name+'.'+src_ext) #print src_path #print tgt_path #print src_crs #print crs cmd = ' '.join(["ogr2ogr", "-f","'ESRI Shapefile'","-s_srs",src_crs,"-t_srs",crs,"'"+tgt_path+"'","'"+src_path+"'"]) #print cmd #try: #it is necessary try: process = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) print process.stdout.read() except: oeq_global.OeQ_push_error('nodeClipByShapefile :',"ogr2ogr failed to run -clipsrc !") #subprocess.call(cmd,shell=True) #except: #oeq_global.OeQ_wait(3) try: layer_interaction.remove_filegroup(src_dir,bu_name,ignore=['qml']) except: pass #print bu_path try: layer_interaction.rename_filegroup(src_dir,src_name,bu_name,ignore=['qml']) except: pass try: layer_interaction.rename_filegroup(src_dir,tgt_name,src_name,ignore=['qml']) except: pass #node.parent().removeChildNode(node) #print bu_path iface.addVectorLayer(src_path,name, 'ogr') oeq_global.OeQ_wait_for_renderer() newnode=nodeByName(name) if newnode: return newnode[0] return None
def nodeClipByShapefile(node,clip_filepath=None,target_filepath=None): import os, subprocess from qgis.core import QgsMessageLog from mole import oeq_global from mole.qgisinteraction import layer_interaction #add path in case ogr2ogr can not be found #check if a clippath is given if clip_filepath == None: return None #if node is a string get the according node if oeq_global.isStringOrUnicode(node): node = nodeByName(node) if len(node) == 0: return None node = node[0] #source CRS src_crs = node.layer().crs().authid() src_layer_name = node.layer().name() src_layer_filepath = node.layer().source() #remove sourcenode from the qgislegend nodeRemove(node) src_dir =os.path.dirname(src_layer_filepath) src_name = os.path.basename(src_layer_filepath).split('.')[0] src_ext = src_layer_filepath.split('.')[1] bu_name= src_name+'_before_clip' bu_path = os.path.join(src_dir,bu_name+'.'+src_ext) #convert original to backup if not target_filepath: #remove older backups layer_interaction.remove_filegroup(src_dir,bu_name,ignore=['qml']) #rename original to backup layer_interaction.rename_filegroup(src_dir,src_name,bu_name,ignore=['qml']) oeq_global.OeQ_wait_for_file(bu_name) ret=subprocess.call(["ogr2ogr", "-f", "ESRI Shapefile","-clipsrc", clip_filepath, src_layer_filepath, bu_path]) if ret!=0: QgsMessageLog.logMessage("nodeClipByShapefile : ogr2ogr failed to run -clipsrc(1) !",'Error in nodeClipByShapefile', QgsMessageLog.CRITICAL) oeq_global.OeQ_push_error('nodeClipByShapefile :',"ogr2ogr failed to run -clipsrc(1) !") return None oeq_global.OeQ_wait_for_file(src_layer_filepath) newlayer = iface.addVectorLayer(src_layer_filepath,src_layer_name, 'ogr') oeq_global.OeQ_wait_for_renderer() else: target_name = os.path.basename(target_filepath).split('.')[0] #check if it is filename or filepath if os.path.basename(target_filepath) == target_filepath: target_filepath=os.path.join(src_dir,target_filepath) target_dir = os.path.dirname(target_filepath) #remove old clip files layer_interaction.remove_filegroup(target_dir,target_name,ignore=['qml']) ret = subprocess.call(["ogr2ogr", "-f", "ESRI Shapefile","-clipsrc", clip_filepath, target_filepath, src_layer_filepath]) if ret!=0: QgsMessageLog.logMessage("nodeClipByShapefile : ogr2ogr failed to run -clipsrc(2) !",'Error in nodeClipByShapefile', QgsMessageLog.CRITICAL) oeq_global.OeQ_push_error('nodeClipByShapefile :',"ogr2ogr failed to run -clipsrc(2) !") return None oeq_global.OeQ_wait_for_file(target_filepath) newlayer = iface.addVectorLayer(target_filepath,src_layer_name, 'ogr') oeq_global.OeQ_wait_for_renderer() if not newlayer: QgsMessageLog.logMessage("nodeClipByShapefile : Could not open layer '"+str(target_filepath)+"' !",'Error in nodeClipByShapefile', QgsMessageLog.CRITICAL) oeq_global.OeQ_push_error('nodeClipByShapefile :',"Could not open layer '"+str(target_filepath)+"' !") return None newlayer.setCrs(QgsCoordinateReferenceSystem(int(src_crs.split(':')[1])), QgsCoordinateReferenceSystem.EpsgCrsId) newnode = nodeByLayer(newlayer) if not newnode: QgsMessageLog.logMessage("nodeClipByShapefile : Could not find node for new layer!",'Error in nodeClipByShapefile', QgsMessageLog.CRITICAL) oeq_global.OeQ_push_error('nodeClipByShapefile :',"Could not find node for new layer!") return None return newnode[0]