5

I'm trying to extract the coordinates of a feature vertex. When I write on my editor

print(vertex)

what I get is

<QgsGeometry: Point(58746.43000004297, -256665.088999123)>

But when I try to extract the coordinates,

print(vertex.x)

I get:

AttributeError: 'QgsGeometry' object has no attribute 'x'

How do I extract the coordinates x, and y?

If it is not possible with <QgsGeometry: Point(x,y)>, then how do I simply convert to a form that allows me to extract the coordinates?

Taras
  • 32,823
  • 4
  • 66
  • 137

1 Answers1

9

I could get the same exception AttributeError:

Traceback (most recent call last):
  File "C:\OSGeo4W\apps\Python39\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 4, in <module>
AttributeError: 'QgsGeometry' object has no attribute 'x'

after running the following code:

from qgis.core import QgsGeometry

vertex = QgsGeometry.fromPointXY(QgsPointXY(58746.43000004297, -256665.088999123)) print(vertex.x)

When one types print(type(vertex)) it returns you a QgsGeometry class.

There are several approaches you may get the x and y coordinates of a vertex/point:

  1. One way is to convert the QgsGeometry class into a QgsPointXY class using the asPoint() method and then using two others methods x() and y() to get your coordinates.

    from qgis.core import QgsGeometry, QgsPointXY
    

    geom = QgsGeometry.fromPointXY(QgsPointXY(58746.43000004297, -256665.088999123)) pt = geom.asPoint() # QgsPointXY print(pt.x(), pt.y())

  2. From another side the QgsGeometry class possess a vertexAt() method that will return a QgsPoint representing a vertex at a certain index. I have not seen your features, but most likely each QgsGeometry is not a multi-part, which means each contains only one point. Hence, one may simply approach each geometry via a 0-index and afterwards use the x() and y() methods again.

    from qgis.core import QgsGeometry, QgsPointXY
    

    geom = QgsGeometry.fromPointXY(QgsPointXY(58746.43000004297, -256665.088999123)) pt = geom.vertexAt(0) # QgsPoint print(pt.x(), pt.y())

  3. There is a constGet() method of the QgsGeometry class available.

    Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.

    from qgis.core import QgsGeometry, QgsPointXY
    

    geom = QgsGeometry.fromPointXY(QgsPointXY(58746.43000004297, -256665.088999123)) geom_ = geom.constGet() print(geom_.x(), geom_.y())

All the above solutions will return the same output:

58746.43000004297 -256665.088999123

References:

Taras
  • 32,823
  • 4
  • 66
  • 137