1

I have a CSV edge list such as follows:

Lat1,Lon1,Lat2,Lon2
93.41823,-104.324324,93.41828,-104.324320
93.40110,-104.310552,93.40108,-104.310557
...

Is there a way to import such a CSV file into QGis such that the edges show up as lines?

1

Replace test.csv with the correct filename and paste the following code into the Python console. Note, that in your csv Lat=y comes before Lon=x.

# specify your csv-file
csvFile = "G:/test.csv"

# create an empty memory layer for polylines
layer = QgsVectorLayer('LineString?crs=EPSG:4326', 'Connected', 'memory')
prov = layer.dataProvider()

# add layer to the map
QgsMapLayerRegistry.instance().addMapLayer(layer)

# open the csv-file for reading and skip the header row
lineStrings = open(csvFile, "rU")
next(lineStrings)

# start editing
layer.startEditing()

# loop over the lines, split them into 4 coordinates, build points from pairs of
# them, and connect the pair of points 
feats = []
for line in lineStrings:
    lineStringAsList = line.split(",")
    from_node = QgsPoint(float(lineStringAsList[1]),float(lineStringAsList[0]))
    to_node = QgsPoint(float(lineStringAsList[3]),float(lineStringAsList[2]))
    feat = QgsFeature()
    feat.setGeometry(QgsGeometry.fromPolyline([from_node, to_node]))
    feats.append(feat)

# finally add all created features and save edits
prov.addFeatures(feats)
layer.updateExtents()
layer.commitChanges()

Please check your latitude values, they are out of range [-90, 90].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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