6

I have two Python list latitude and longitude which stores the coordinates, and I want to draw a single line from the list coordinates.

I can draw the line if I know the number of latitude/longitude.

# suppose the line is having 2 longitudes and 2 latitudes.
QgsFeature().setGeometry(QgsGeometry.fromPolylineXY([QgsPointXY(78.3022187,23.7875547),QgsPointXY(98.3022187,33.7875547)]))

# suppose the line is having 3 longitudes and 3 latitudes.
QgsFeature().setGeometry(QgsGeometry.fromPolylineXY([QgsPointXY(78.3022187,23.7875547),QgsPointXY(98.3022187,33.7875547),QgsPointXY(148.3022187,133.7875547)]))

How can I draw a line in QGIS through Python, for the variable number of points?

2
  • 3
    You have already drawn a line from variable number of points. What exactly do you want to know? Commented Jan 4, 2021 at 14:47
  • we have two python list 'latitude' and 'longitude' which stores the co-ordinates, and i want to draw a single line from the list co-ordinates.
    – Arm
    Commented Jan 5, 2021 at 3:55

1 Answer 1

5

At this point, Python zip function comes into play.

layer = iface.activeLayer()
layer.startEditing()

longitudes = [5, 10, 15, 20]
latitudes = [5, 10, 5, 10]

### zip function in list comprehension
coords = [QgsPointXY(lon, lat) for lon, lat in zip(longitudes, latitudes)]
###

feature = QgsFeature()
line = QgsGeometry.fromPolylineXY(coords)
feature.setGeometry(line)

layer.addFeature(feature)
layer.commitChanges()

enter image description here

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.