2

I have created new temporary layers with selected features for the two layers .Then I am trying to do union of the two said temporary layers.

temporary layer1

      if ('Districts'==layer.name()):
            val=int(layer.type())
            provider = layer.dataProvider()

            # Get the currently selected layer
            inLayer = layer

            inFields = inLayer.dataProvider().fields()

            inLayerGeometryType = ['Point','Line','Polygon'][inLayer.geometryType()]

            # Convert its CRS to a string we can pass to QgsVectorLayer's constructor
            inLayerCRS = inLayer.crs().authid()

            # Make the output layer

            outLayer = QgsVectorLayer(inLayerGeometryType + '?crs='+inLayerCRS, 'dp_Slope', 'memory')

            # Copy the fields from the old layer into the new layer
            outLayer.startEditing()
            outLayer.dataProvider().addAttributes(inFields.toList())
            outLayer.commitChanges()

            # Add it to the map

##                inFields = layer.dataProvider().fields()
##                writer = QgsVectorFileWriter( "temp_Slope.shp", provider.encoding(), provider.fields(),QGis.WKBPolygon, provider.crs() )
##                newlayer = iface1.addVectorLayer("temp_Slope.shp", "temp_Slope.shp", "ogr")

            if (val==0):
                iface1.setActiveLayer(layer)
                v=[self.listWidget_SlopeDrought.item(i) for i in range(self.listWidget_SlopeDrought.count())]
                flag=0
                selects=[]
                for i in range(self.listWidget_SlopeDrought.count()):
                    v=self.listWidget_SlopeDrought.item(i) 
                    state=v.checkState()
                    if state==2 and self.groupBox_slopeDrought.isChecked():
                        flag=1
                        value=self.listWidget_SlopeDrought.item(i).text()
                        query=" \"{}\" {} '{}' ".format(value1,"=",value)
                        selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
                        layer.setSelectedFeatures([k.id() for k in selection])

                        ourFeat = QgsFeature()
                        for feat in layer.selectedFeatures():
                            ourFeat.setGeometry(feat.geometry())
                            ourFeat.setAttributes(feat.attributes())
                            j=outLayer.dataProvider().addFeatures([ourFeat])
                            outLayer.updateExtents()
                if flag==1:
                    QgsMapLayerRegistry.instance().addMapLayer(outLayer)
                    QgsVectorFileWriter.writeAsVectorFormat(outLayer, 'dp_Slope.shp', "utf-8", None, "ESRI Shapefile")
                    layer.removeSelection()
                    self.tabWidget.setTabEnabled (1, True)
                    self.tabWidget.setCurrentIndex(1)
                    QtGui.QMessageBox.information(self,"Layer Created!","Temporary layer for Slope created as dp_Slope")
                    self.groupBox_slopeDrought.setEnabled(False)
                    self.pushButton_nextSlopeDrought.setEnabled(False)
                    #self.pushButton_ResetCheckDam_slope.setEnabled(True)
                    flag=0
                    #self.label_alreadyCreated_slope_cd.show()
                    #self.tabWidget.setTabEnabled (0, False)
                elif flag==0 and self.groupBox_slopeDrought.isChecked():
                    QtGui.QMessageBox.warning(self,"No value selected!","Please select value(s) to create layer")
                else:
                    self.tabWidget.setTabEnabled (1, True)
                    self.tabWidget.setCurrentIndex(1)

temporary layer2

if ('Soil'==layer.name()):
            val=int(layer.type())
            provider = layer.dataProvider()

            # Get the currently selected layer
            inLayer = layer
            # Get its list of fields
            inFields = inLayer.dataProvider().fields()

            # Convert its geometry type enum to a string we can pass to
            # QgsVectorLayer's constructor
            inLayerGeometryType = ['Point','Line','Polygon'][inLayer.geometryType()]

            # Convert its CRS to a string we can pass to QgsVectorLayer's constructor
            inLayerCRS = inLayer.crs().authid()

            # Make the output layer

            outLayer = QgsVectorLayer(inLayerGeometryType + '?crs='+inLayerCRS, 'dp_Soil', 'memory')

            # Copy the fields from the old layer into the new layer
            outLayer.startEditing()
            outLayer.dataProvider().addAttributes(inFields.toList())
            outLayer.commitChanges()

            if (val==0):
                iface1.setActiveLayer(layer)

                value=self.doubleSpinBoxSoilDrought.value()

                query=" \"{}\" {} '{}' ".format(value1,"<",value)

                selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
                layer.setSelectedFeatures([k.id() for k in selection])

                ourFeat = QgsFeature()
                for feat in layer.selectedFeatures():
                    ourFeat.setGeometry(feat.geometry())
                    ourFeat.setAttributes(feat.attributes())
                    j=outLayer.dataProvider().addFeatures([ourFeat])
                    outLayer.updateExtents()

                if value and self.groupBox_soilDrought.isChecked():
                    QgsMapLayerRegistry.instance().addMapLayer(outLayer)
                    QgsVectorFileWriter.writeAsVectorFormat(outLayer, 'dp_Soil.shp', "utf-8", None, "ESRI Shapefile")
                    layer.removeSelection()
                    self.tabWidget.setTabEnabled (2, True)
                    self.tabWidget.setCurrentIndex(2)
                    QtGui.QMessageBox.information(self,"Layer Created!","Temporary layer for soil created as dp_Soil")

                    self.groupBox_soilDrought.setEnabled(False)
                    self.pushButton_nextSoilDrought.setEnabled(False)
                    self.operations()

                elif not value and self.groupBox_soilDrought.isChecked():
                    QtGui.QMessageBox.warning(self,"No value selected!","Please select value(s) to create layer")
                elif not self.groupBox_soilDrought.isChecked():
                    self.tabWidget.setTabEnabled (2, True)
                    self.tabWidget.setCurrentIndex(2)

Then I m doing union

operation='qgis:union'
val1='dp_Slope'
val3='dp_Soil'
val4='result_dp'
processing.runalg(operation,val1,val3, val4+".shp")
layerAdded = iface1.addVectorLayer(os.getcwd(),'result_dp', "ogr")
QgsMapLayerRegistry.instance().addMapLayer(layerAdded )
  • Are you trying to load the two temporary layer in qgis? Are they correct? Do you reach to do the Union by the gui? – Oscar Campo Mar 14 '18 at 8:53
  • ya I m trying through gui.. – drama Mar 14 '18 at 9:13
1

Actually found a easier way to create layer from selected features of layer..

QgsVectorFileWriter.writeAsVectorFormat( layer, "dp_Slope.shp", "utf-8", layer.crs(), "ESRI Shapefile", 1) #1 is for creating layer using selected features
vlayer = QgsVectorLayer(os.getcwd()+"/dp_Slope.shp", "dp_Slope", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(vlayer) #loading layer

but anyway the problem was with loading the layer separately after doing union

solved it by using

processing.runandload(operation,val1,val3, val4+".shp")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.