##Points=vector point ##Only_use_selected_points=boolean False ##Line=vector line ##Only_use_selected_lines=boolean False ##step=number 1 from qgis.core import * from qgis.PyQt.QtCore import QVariant layer1 = processing.getObject(Points) crs = layer1.crs().toWkt() layer2 = processing.getObject(Line) if Only_use_selected_lines: line_feats = layer2.selectedFeatures() else: line_feats = layer2.getFeatures() for ft in line_feats: index = QgsSpatialIndex() tmp_points = {} line_geom = ft.geometry() len = line_geom.length() current = 0 # This layer contains all the points created along the line (it isn't an output) temp_pts = QgsVectorLayer('Point?crs='+ crs, 'temp_pts' , 'memory') prov = temp_pts.dataProvider() # Uncomment the next line if you want to see the 'temp_pts' layer #QgsMapLayerRegistry.instance().addMapLayer(temp_pts) while current < len: point = line_geom.interpolate(current) # Create a point along the line at the current distance fet = QgsFeature() fet.setGeometry(point) (result, feat) = prov.addFeatures([fet]) tmp_points[feat[0].id()] = current index.insertFeature(feat[0]) current += step # Increase the distance by the step provided # This layer is the final output which stores the distances from the closest point along the line and the start/end of the line out = 'output_%s' % (ft.id()) output = QgsVectorLayer('Point?crs='+ crs, out, 'memory') prov2 = output.dataProvider() fields = layer1.pendingFields() # Fields from the input layer fields.append(QgsField('DIST_START', QVariant.Double, '', 10, 3)) # Name for the new field in the output layer fields.append(QgsField('DIST_END', QVariant.Double, '', 10, 3)) # Name for the new field in the output layer prov2.addAttributes(fields) # Add input layer fields to the outLayer output.updateFields() if Only_use_selected_points: point_feats = layer1.selectedFeatures() else: point_feats = layer1.getFeatures() for feat in point_feats: geom = feat.geometry() attrs = feat.attributes() nearest = index.nearestNeighbor(geom.asPoint(), 1) dist_start = tmp_points[nearest[0]] attrs.append(dist_start) dist_end = len - tmp_points[nearest[0]] attrs.append(dist_end) outGeom = QgsFeature() outGeom.setGeometry(geom) outGeom.setAttributes(attrs) prov2.addFeatures([outGeom]) # Add the 'output' layer to the Layers panel QgsMapLayerRegistry.instance().addMapLayer(output)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question