On Fri, Jan 14, 2011 at 8:39 PM, Gary Smith <gary.smith....@gmail.com> wrote: > Hello, > > I am not sure whether this is the right forum but extensive Google searches > have not helped. I am writing a plugin to convert the segments of a polyline > to a layer of individual 2 vertex line features. > > This is the code I used to do the job > > feat = QgsFeature() > p = 0 > while p < cl.featureCount(): > cl.featureAtId(p, feat, True, True) > geom0 = QgsGeometry(feat.geometry()) > vl = QgsVectorLayer("LineString", "Mylines", "memory") > provider = vl.dataProvider() > provider.addAttributes( [ QgsField( "id" , QVariant.String), > QgsField( "agl" , QVariant.String) ]) > pnt10 = QgsPoint( geom0.vertexAt(0) ) > segfeat = QgsFeature() > itr = 1 > while ( QgsPoint( geom0.vertexAt(itr) ) <> QgsPoint(0,0) ): > pnt10 = QgsPoint( geom0.vertexAt(itr -1) ) > pnt11 = QgsPoint( geom0.vertexAt(itr) ) > newGeom = QgsGeometry.fromPolyline( [ pnt10, pnt11 ] ) > segfeat.setGeometry( newGeom ) > segfeat.setAttributeMap( { 0 : QVariant( str(itr) ), 1 : > QVariant( str(agl) ) } ) > provider.addFeatures( [segfeat] ) > itr += 1 > p += 1 > vl.commitChanges() > QgsMapLayerRegistry.instance().addMapLayer(vl)
Hi Gary I'm not sure what exactly you are trying to do. From the code snippet it looks that for each feature of the original layer you create a new layer! That's probably not what you want, is it? I have few more suggestions: - iterate over the input using select() and nextFeature() methods instead of featureAtId(). Generally IDs of features are not increasing from 0. The former approach guarantees you that you will not miss any features - to work with geometry, you can call geometry's asPolyline() method to get a list of points - more convenient than calling vertexAt() - no need to call vl.commitChanges() since you do changes directly to the provider Martin _______________________________________________ Qgis-user mailing list Qgis-user@lists.osgeo.org http://lists.osgeo.org/mailman/listinfo/qgis-user