PyQGIS – How to Create a Polygon from a CSV File with Coordinates

convertcsvpyqgispyqgis-3

I like a write a script which:

  1. Imports a CSV file that contains a series of points (latitude and longitude) into QGIS
Lat Long
56.99181358 -111.4801108
56.98924901 -111.4764563
56.98591437 -111.471848
56.98195783 -111.4725851
56.98184493 -111.4796676
56.98629477 -111.4847629

Here are the points when I import them into the QGIS. I want to create one polygon using these points.

enter image description here

  1. Create a polygon from imported points and finally create a shapefile.

Here is how I did part 1:

uri = "file:///C:/Users/katala/Desktop/PyQGIS/Tailings Pond 1A.csv?encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s" % ("UTF-8",",", "Lat", "Long","epsg:4326")

#Make a vector layer
eq_layer=QgsVectorLayer(uri,"eq-data","delimitedtext")

#Check if layer is valid
if not eq_layer.isValid():
    print ("Layer not loaded")

#Add CSV data    
QgsProject.instance().addMapLayer(eq_layer)

But I don't know how to do the second part and create a polygon. I found the following code, but I don't know how to adjust it to read the points from the generated vector layer.

polygon.setToGeometry(QgsGeometry.fromPolygonXY([**p_points**]),None) 

Best Answer

Read the attributes into a list of QGSPointXY's using getFeatures :

points = [QgsPointXY(f['long'], f['lat']) for f in iface.activeLayer().getFeatures()]
poly = QgsGeometry.fromPolygonXY([points]) #Create a polygon geometry

#Create a empty memory layer
vl = QgsVectorLayer("Polygon?crs=EPSG:4326&index=yes", "myLayer", "memory")
provider = vl.dataProvider()

newfeature = QgsFeature()
newfeature.setGeometry(poly)
provider.addFeature(newfeature)
QgsProject.instance().addMapLayer(vl)

(Nevermind my comment that a polygon has to start and stop in the same coordinate: Note that unlike some programs, QGIS will close the ring for you so there is no need to duplicate the first point as the last.)

enter image description here

Related Question