5

I need to get the first and the last vertex from a multilinestring layer from PostGIS and create a memory point layer with them. The code below works for some line layers and doesn't for others in QGIS 3.6 and I can't figure out why. When I run it in QGIS 3.4 it simply doesn't work and don't get any error message.

line_lyr = qgis.utils.iface.activeLayer()
feat = QgsFeature()

point_layer = QgsVectorLayer("Point?crs=epsg:31984", "point_layer", "memory")
pr = point_layer.dataProvider()

for feature in line_lyr.getFeatures():
  geom = feature.geometry().asMultiPolyline()
    for line in geom:
      start_point = QgsPointXY(geom[0][0])
      end_point = QgsPointXY(geom[-1][-1])
      feat.setGeometry(QgsGeometry.fromPointXY(start_point))
      pr.addFeatures([feat])
      feat.setGeometry(QgsGeometry.fromPointXY(end_point))
      pr.addFeatures([feat])

QgsProject.instance().addMapLayer(point_layer)

I had missed something in the code? How can I improve this code for PyQGIS3?

7
  • Possible duplicated gis.stackexchange.com/questions/208831/…
    – Fran Raga
    Jun 28, 2019 at 8:04
  • Your code should work fine for MultiLineString geometry types. Did you check if all layers are of the same type? Do you receive an output if you run it in 3.4? Are there attributes stored?
    – Joseph
    Jun 28, 2019 at 11:01
  • 1
    @FranRaga, thanks for your comment. I'll improve the question title, so the link you posted is related to a question about how to get the points, and I know how to get the points but I want to figure out why this code doesn't works for certain line layers and for a specific QGIS version. Jun 28, 2019 at 11:17
  • 2
    @FranciscoCamello - I guess there are some null geometries in your roads layer. Try adding an if statement if feature.geometry() is not None: directly after the line for feature in line_lyr.getFeatures(): and indent accordingly. This should ignore null geometries.
    – Joseph
    Jun 28, 2019 at 11:42
  • 1
    Thanks @Joseph, the if statement works fine, but, I've run some of topology/geometry tools and I've found and correct null geometrys, even so I leave the if statement in the code. Feel free to answer the question, if you want, this way I can rate it as correct. Jun 30, 2019 at 12:40

1 Answer 1

1

With regards to the comments, the geometries could contain errors or be Null. Run geometric-reparing tools to try and fix existing errors.

Additionally, inserting the following if statement ignores all null geometries in the current feature and continues with the next:

for feature in line_lyr.getFeatures():
    if feature.geometry() is not None:
        geom = feature.geometry().asMultiPolyline()
        ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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