I have four coordinates: north, south, east and west. How can I automatically create a bounding box in my shapefile? Can I do it through Python?
1 Answer
Yes. Use this structure:
# make new memory layer
crs = 'EPSG:4326' # specify the crs of coordinates
layer = QgsVectorLayer(f"Polygon?crs={crs}", "LAYER_NAME", "memory")
QgsProject.instance().addMapLayer(layer)
# specify coordinates
north = [0, 0]
west = [0, 1]
south = [1, 1]
east = [1, 0]
# construct box geometry
geom = QgsGeometry.fromPolygonXY([[
QgsPointXY(*north),
QgsPointXY(*west),
QgsPointXY(*south),
QgsPointXY(*east)
]])
# make feature
feature = QgsFeature()
feature.setGeometry(geom)
# add the feature to the layer
layer.dataProvider().addFeatures([feature])