0

I have a .shp with points which have unique IDs based on which I want to connect them. When I run the code, it creates empty line layers without geometry.

layer = QgsProject.instance().mapLayersByName("shap")[0]
features = layer.getFeatures()
hodList=[]
for feat in features:
    ids=feat['shape_id']
    hodList.append(ids)
unikatniId=list(set(hodList))

for i in unikatniId:
    expression = ('"shape_id" LIKE \'%s%s\''%(i,'%'))
    request = QgsFeatureRequest().setFilterExpression(expression)
    PointList = []
    v_layer = QgsVectorLayer("LineString?crs=epsg:4326", "line", "memory")
    pr = v_layer.dataProvider()
    line=QgsFeature()
    for f in layer.getFeatures(request):
        termino = QgsPoint(feat['shape_pt_lon'],feat['shape_pt_lat'])
        PointList.append(termino)
        line.setGeometry(QgsGeometry.fromPolyline(PointList))
        pr.addFeatures( [ line ] )
        v_layer.updateExtents()
        QgsProject.instance().addMapLayers([v_layer])

0

There are a few logical errors in your code. Please see the updated code with comments for explanation:

layer = QgsProject.instance().mapLayersByName("shap")[0]
features = layer.getFeatures()
hodList=[]
for feat in features:
    ids=feat['shape_id']
    hodList.append(ids)
unikatniId=list(set(hodList))


v_layer = QgsVectorLayer("LineString?crs=epsg:4326", "line", "memory")
pr = v_layer.dataProvider()
## I do believe that you want to store resulting lines in one layer,
## so these lines should be moved from internal for loop


for i in unikatniId:
    expression = ('"shape_id" LIKE \'%s%s\''%(i,'%'))
    request = QgsFeatureRequest().setFilterExpression(expression)
    PointList = []

    line=QgsFeature()
    for f in layer.getFeatures(request):

        termino = QgsPoint(f['shape_pt_lon'],f['shape_pt_lat']) #I do understand that shape_pt_lon and shape_pt_lat are columns containing coordinates 
        ## definitely you want to use f rather then feat. 
        ## Feat was returning last scanned point,
        ## that is why you were getting empty lines
        ## (actually they were lines consisting of one point) 

        PointList.append(termino)

    line.setGeometry(QgsGeometry.fromPolyline(PointList))
    pr.addFeatures( [ line ] )
    ## indenting might be reason of logical errors.
    ## You probably want to add line only once for given unikatniId
    ## so take it outside of "f" loop

v_layer.updateExtents()
QgsProject.instance().addMapLayers([v_layer])
## And finally add shape to MapLayers, but only once
## (if you want to have one layer with resulting lines)
| improve this answer | |

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.