TransWikia.com

Create empty geometry in QGIS with Python

Geographic Information Systems Asked by Philip Whitten on February 27, 2021

I would like to create a model point dataset in QGIS 3.0.3 with Python in the QGIS python console to do some testing. Specifically, I want to create a point dataset that has a feature with an empty geometry, and, another feature with a null geometry.

What I have tried is:

layer = QgsVectorLayer('Point?crs=epsg:4326&field=id:string&field=type:string','ModelPoints',"memory")
pr = layer.dataProvider()

points = {}
points['Pt1'] = ['(1,1)', QgsPointXY(1,1)]
points['Pt2'] = ['(2,1)', QgsPointXY(1,1)]
points['Pt3'] = ['(4,1)', QgsPointXY(1,1)]
points['Pt4'] = ['empty', QgsPointXY()]
points['Pt5'] = ['null', None]

for id, point in points.items():
    pt = QgsFeature()   
    pt.setAttributes([id,point[0]])
    if point[1] is not None:
        pt.setGeometry(QgsGeometry.fromPointXY(point[1]))
    print(pt.geometry().asWkt())    
    pr.addFeature(pt)

layer.updateExtents()
QgsProject.instance().addMapLayer(layer)

In this code, the empty point geometry is intended to be created by:

pt.setGeometry(QgsGeometry.fromPointXY(QgsPointXY())

However, the result is:

pt.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(0,0))

So, my code is making a point with the vertex (0,0), but, whereas I need a point (or a geometry) with no vertices.

Note: The approaches g = QgsGeometry.fromWkt('POINT') and g = QgsGeometry.fromWkt('POINT EMPTY') both result in a null geometry as shown by using print(g.isNull()).

3 Answers

One approach to creating an empty geometry is:

QgsGeometry.fromWkt('LineString()')

These can be tested by:

QgsGeometry.fromWkt('LineString()').isEmpty()
True
QgsGeometry.fromWkt('LineString()').isNull()
False

However, for an empty point, QGIS is currently displaying:

> QgsGeometry.fromWkt('Point()').isNull()
True

So, empty line data sets can be constructed, but, there maybe an error for empty point datasets.

Correct answer by Philip Whitten on February 27, 2021

This creates a generic null geometry:

QgsGeometry().fromWkt('')

Qgis 3.10.5

Answered by cefect on February 27, 2021

Sorry, if it's obvious, but you can simply create an instance of QgsGeometry without arguments.

For example

geo= QgsGeometry()
geo.isNull()
     True

Answered by Luis Perez on February 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP