2

I'm using this script that draws a perpendicular line between a point and the nearest line segment, but when I use the Python terminal and paste the script, I get an error:

Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 3, in <module>
ValueError: min() arg is an empty sequence

below the code:

from qgis.core import QgsProject

mapcanvas = iface.mapCanvas()

layers = mapcanvas.layers()

p_lyr = layers[0] l_lyr = layers[1]

epsg = p_lyr.crs().postgisSrid()

uri = "LineString?crs=epsg:" + str(epsg) + "&field=id:integer""&field=distance:double(20,2)&index=yes"

dist = QgsVectorLayer(uri, 'dist', 'memory')

QgsProject.instance().addMapLayer(dist)

prov = dist.dataProvider()

lines_features = [ line_feature for line_feature in l_lyr.getFeatures() ] points_features = [ point_feature for point_feature in p_lyr.getFeatures() ]

feats = []

for p in points_features:

minDistPoint = min([l.geometry().closestSegmentWithContext( p.geometry().asPoint() ) for l in lines_features])[1]
feat = QgsFeature()
feat.setGeometry(QgsGeometry.fromPolyline([QgsPoint(p.geometry().asPoint()), QgsPoint(minDistPoint)]))
feat.setAttributes([points_features.index(p),feat.geometry().length()])
feats.append(feat)

prov.addFeatures(feats)

What might be happening and how to correct it?

Below is an image of what I'm trying to do.

enter image description here

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
  • 2
    Have you seen https://gis.stackexchange.com/questions/365737/connecting-lines-with-point-in-qgis/365744#365744 . Have you made sure you have points, len(points_features) and also lines? – BERA Aug 18 '21 at 12:00
  • As I do understand your code, the first layer in the project should be the point layer and the 2nd should be the line layer. Basic debugging would then be as BERA said above to check if you really have the points and lines you think you have gotten. Do some basic debugging: After the line_features= and point_features= lines, add two lines print(len(line_features)) and print (len(point_features)). When doing that and setting up a project with a point coverage as the first layer and a line coverage as the secound layer, this tells me that I have no lines in the line_features. – MortenSickel Aug 18 '21 at 12:24
  • 3
    thank you very much, that was the problem, my point feature was as MultiPoint, when I exported only to Point, the script worked. – Marcelo Teixeira Aug 18 '21 at 12:37

0 Answers0