How to get shape geometry type in PyQgis

I am writing a script that depends on knowing the type of geometry of the loaded shapefile. but I looked in the cookbook and pyqgis API and cannot figure out what to call it.

infact, I find it difficult to interpret the API, so any light shed on this topic will be appreciated.

thanks

+5
source share
3 answers

The command is simple:

layer=qgis.utils.iface.mapCanvas().currentLayer() if layer.wkbType()==QGis.WKBPoint: print 'Layer is a pojnt layer' if layer.wkbType()==QGis.WKBLineString: print 'Layer is a line layer' if layer.wkbType()==QGis.WKBPolygon: print 'Layer is a polygon layer' if layer.wkbType()==QGis.WKBMultiPolygon: print 'Layer is a multi-polygon layer' if layer.wkbType()==100: print 'Layer is a data-only layer' 

you can use numbers (1,2,3,4) instead of QGis.WKB ***** sintax, but the method described above gives more readable code.

The actual reference in the cookbook is here: http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/geometry.html

+6
source

QgsGeometry has a wkbType method that returns what you want.

+1
source

You are looking for a way to have the type of geometry in the string and after multiple searches, finally found a clean method in the documents:

 geomTypeString=qgis.core.QgsWKBTypes.displayString(int(layer.wkbType())) 

which will give "Point", "LineString", "Polygon", "MultiPoint" .... and he "knows" all types of geometry in Qgis.

For my purpose, I still had problems with "Point25D" and other weird types, so I added this to limit them to flat (Point, Line, Poly)

 geomFlatTypeString=qgis.core.QgsWKBTypes.displayString(int( qgis.core.QgsWKBTypes.flatType(int(in_layer.wkbType())))) 

For information, the goal was a method that duplicates a memory layer for any type, here is the complete code:

 def copyLayer(in_layer,condition=None): #condition=function to test features and return True or False______ if condition==None: def condition(f): return True typeGeom=qgis.core.QgsWKBTypes.displayString(int( qgis.core.QgsWKBTypes.flatType(int(in_layer.wkbType())))) crsId=in_layer.crs().authid() out_layer=QgsVectorLayer(typeGeom+"?crs="+crsId, in_layer.name()+"_copie", "memory") fields=in_layer.dataProvider().fields().toList() out_layer.dataProvider().addAttributes(fields) out_layer.updateFields() features=[f for f in in_layer.getFeatures() if condition(f)] out_layer.dataProvider().addFeatures(features) return out_layer 
+1
source

Source: https://habr.com/ru/post/1200161/


All Articles