2

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.

Taras
  • 32,823
  • 4
  • 66
  • 137

1 Answers1

6

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]]

enter image description here

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)

enter image description here

Taras
  • 32,823
  • 4
  • 66
  • 137
BERA
  • 72,339
  • 13
  • 72
  • 161