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) 
4
  • I added the sample data to the question
    – ali katal
    Commented Mar 9, 2022 at 12:33
  • 2
    Please add the data as formatted text. Currently there is no way to copy it without typing it out, and it is unlikely anyone will do that. See here for how to create a table in your question (or use an online converter such as tablesgenerator.com/markdown_tables).
    – Matt
    Commented Mar 9, 2022 at 12:42
  • Thanks @Matt . I added data as formatted text.
    – ali katal
    Commented Mar 9, 2022 at 13:45
  • @BERA it's actually one polygon. I added the points to my question for clarification. If start and end points must be the same to create the polygon I can copy the first point to the end.
    – ali katal
    Commented Mar 9, 2022 at 13:46

1 Answer 1

3

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.