3

I would like to identify the start- and endpoints within a set of polylines and return the coordinates of both points finally.

So far i have been able to iterate the features and found out that ArcGIS's export created a MulitLineString with a number of vertices (where the number corresponds to the length of the line).

Using feature.geometry().vertexAt(0) (where feature is the current feature within a for loop) returns the first point of every feature and the print-result looks like that <QgsPoint: Point (4800744.81731882505118847 2812251.2178244274109602)> but i didn't find a way to set up a "for vertex in vertices"-style iteration to get the last point of every line.

The Python2.x-style from Can vector layer get start point and end point of line using PyQGIS with

geom = feature.geometry().asPolyline()
start_point = QgsPoint(geom[0])
end_point = QgsPoint(geom[-1])

doesn't work anymore.asPolyline() seems to return an empty list.

I've tried to iterate the vertices with vertices(self) → QgsVertexIterator but cant get any results. since i am pretty new to PyQGIS the QGIS Python API seems really confusing to me.

Taras
  • 32,823
  • 4
  • 66
  • 137
robert tuw
  • 898
  • 1
  • 9
  • 20

1 Answers1

13

If you're input is a multilinestring, then you'll need to handle that by either iterating through all the parts or (blindly!) just taking the first part alone.

For QGIS <= 3.4:

To take the first part:

multilinestring = feature.geometry().get()
first_part = multilinestring.geometryN(0)
# first_part will be a QgsLineString object

To get the first/last vertices:

first_vertex = first_part.pointN(0)
last_vertex = first_part.pointN(first_part.numPoints()-1)

For QGIS > 3.4:

The API is much easier here. You can use code like this and it'll work for BOTH linestring and multilinestring inputs:

for part in feature.geometry().get():
    first_vertex = part[0]
    last_vertex = part[-1]
ndawson
  • 27,620
  • 3
  • 61
  • 85
  • 3
    I don't know why but in Qgis 3.10 this is only working for me when i use constGet() instead of get(). The api actually recommends to use constGet instead of get anyway: https://qgis.org/pyqgis/3.10/core/QgsGeometry.html?highlight=qgsgeom#qgis.core.QgsGeometry.constGet – Jonathan Oct 10 '20 at 13:42
  • Yes, indeed works with constGet() in Qgis 3.10 – nanunga Mar 07 '23 at 20:01