2

I am attempting to build a layer of perpendicular line segments from a point on a line to a line, but in the process, I would like to bring over the field data from the point layer.

I have a field in p_lyr called Miles. I would like to move that field value to the new layer, in a newly -created field in the new layer.

This is the script I have used so far:

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=distances:double(20,2)&index=yes"
dist = QgsVectorLayer(uri, 'PerpLine', 'memory')
QgsProject.instance().addMapLayer(dist)

prov = dist.dataProvider()

prov.addAttributes(p_lyr.fields())

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.fromPolylineXY([p.geometry().asPoint(), minDistPoint]))
    feat.setAttributes([points_features.index(p),feat.geometry().length()])
    feats.append(feat)

prov.addFeatures(feats)

This comes from a script listed here: Automated creation of perpendicular lines between a point layer and a line layer

I am using QGIS 3.12.

Taras
  • 32,823
  • 4
  • 66
  • 137
Jim Garner
  • 63
  • 7
  • 1
    Try this: 1) Add the new field definition to the uri of the new layer; 2) pass the value (p["your_field"]) to feat.setAttributes() in the order set in the uri. – Germán Carrillo Mar 29 '20 at 14:10
  • Thank you. Trying: 'uri = "LineString?crs=epsg:" + str(epsg) + "&field=id:integer""&field=marker:double(20,2)&field=distances:double(20,2)&index=yes"'

    And this: 'for p in points_features:

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

    prov.addFeatures(feats)'

    – Jim Garner Mar 30 '20 at 02:38
  • invalid syntax on 2nd step line added. – Jim Garner Mar 30 '20 at 02:38
  • feat.setAttributes([points_features.index(p),feat.geometry().length()]) doesn't seem to be receiving the field value you're interested to transfer to the line. You should pass something like p["your_field"] as the second argument (according to your uri definition). – Germán Carrillo Mar 30 '20 at 02:59

0 Answers0