In ArcPy, you can pass a geometry object as parameter to geoprocessing tool:
import arcpy
coordinates = [[20, 30], [30, 30], [30, 20], [20, 20]]
array = arcpy.Array([arcpy.Point(x, y) for x, y in coordinates])
Create a polygon geometry object using the array object
boundary = arcpy.Polygon(array, arcpy.SpatialReference(4326))
arcpy.Clip_analysis('c:/data/rivers.shp',
boundary, # <- GEOMETRY OBJECT
'c:/data/rivers_clipped.shp')
I have a polygon geometry and a layer. I want to clip the layer by the polygon geometry using PyQGIS. Normally, I make a new layer, add the geometry to the layer and use it in processing.run as follows:
coordinates = [QgsPointXY(20, 30), QgsPointXY(30, 30),
QgsPointXY(30, 20), QgsPointXY(20, 20)]
geometry = QgsGeometry.fromPolygonXY([coordinates ])
temp_layer = QgsVectorLayer(f"Polygon?crs=EPSG:4326", "TEST", "memory")
feature = QgsFeature()
feature.setGeometry(geometry)
temp_layer.dataProvider().addFeatures([feature])
temp_layer.updateExtents()
LayerA = iface.activeLayer()
result = processing.run("native:difference",
{'INPUT': LayerA, # <- QgsVectorLayer
'OVERLAY': temp_layer, # <- QgsVectorLayer
'OUTPUT':'TEMPORARY_OUTPUT'})
But I would like to avoid making a new layer for one geometry. I tried passing a geometry to processing.run, but it obviously didn't work:
result = processing.run("native:difference",
{'INPUT': LayerA, # <- QgsVectorLayer
'OVERLAY': geometry, # <- QgsGeometry ?
'OUTPUT':'TEMPORARY_OUTPUT'})
How can I pass a geometry object to a processing tool without making a new layer for the geometry? Is that possible in PyQGIS?
geom2lyrto convert a geometry or list of geometries into a layer, in a library that I import into most of my scripts. Using the geometry directly would be very handy. – Matt Jan 25 '22 at 14:18