In QGIS by means of Python I would like to add a line (polyline) from a CSV file which has the following format for the coordinates:
[[7.89471262378373, 48.405478200932436], [7.896052894441773, 48.41059537964788]]
[[7.89471262378373, 48.405478200932436], [7.892694850981679, 48.40550448264249], [7.887506712484601, 48.40574772233518], [7.878533768291611, 48.4055148846117]]
I would like to know how can I export this data with Python and then, how could I create the line on the map.
-
1Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.Community– Community Bot2022年10月20日 16:03:30 +00:00Commented Oct 20, 2022 at 16:03
-
1This answer may be helpful: gis.stackexchange.com/a/341700/162856wanderzen– wanderzen2022年10月20日 16:26:12 +00:00Commented Oct 20, 2022 at 16:26
1 Answer 1
Read the CSV row by row using the csv
module, create an empty line layer, create and insert LineStrings.
This is the exact contents of my CSV file:
[[7.89471262378373, 48.405478200932436], [7.896052894441773, 48.41059537964788]]
[[7.89471262378373, 48.405478200932436], [7.892694850981679, 48.40550448264249], [7.887506712484601, 48.40574772233518], [7.878533768291611, 48.4055148846117]]
import csv
file = r'/home/bera/Desktop/lines.csv'
#Create empty temp line layer
vl = QgsVectorLayer("LineString?crs=epsg:4326&index=yes", "myLayer", "memory")
provider = vl.dataProvider()
with open(file, newline='') as f:
reader = csv.reader(f)
for row in reader:
#row is a list of strings: ['[[7.89471262378373', ' 48.405478200932436]', ' [7.892694850981679', ' 48.40550448264249]', ' [7.887506712484601', ' 48.40574772233518]', ' [7.878533768291611', ' 48.4055148846117]]']
coordinates = eval(','.join(row)) #Join the string with a comma delimiter and turn into a list with eval
line = QgsGeometry(QgsLineString(coordinates)) #Create a line geometry
f = QgsFeature() #Create a new feature
f.setGeometry(line) #Set the geometry
provider.addFeature(f) #Add it
QgsProject.instance().addMapLayer(vl)
-
1Thank you for your help! I just had a problem loading the file since you used the form r'/file_address and I had to read to find out how it works (I'm new in Python).Paulo Matias Montecinos Medel– Paulo Matias Montecinos Medel2022年10月21日 08:08:57 +00:00Commented Oct 21, 2022 at 8:08
-
Hello again. The line that was created does not have a table with the coordinates that were drawn. How can I add a table with the coordinate values?Paulo Matias Montecinos Medel– Paulo Matias Montecinos Medel2022年11月02日 10:54:14 +00:00Commented Nov 2, 2022 at 10:54
Explore related questions
See similar questions with these tags.