I'm trying to draw random points along the polylines. The polyline layer and the number of points to create are given as input. My problem is that the points are being created for every single line existing in the layer, so if as an input I'm setting 5 points the result is 5 points for every line, not 5 points in general. Below is my code:
import arcpy
from arcpy import mp
import os
import random
arcpy.env.overwriteOutput = True
aprx_path = 'CURRENT'
aprx = mp.ArcGISProject(aprx_path)
map = aprx.listMaps()[0]
# Getting all values from the tool
input_layer = arcpy.GetParameterAsText(0)
output_layer = arcpy.GetParameterAsText(1)
points_nb = arcpy.GetParameterAsText(2)
# Description od input layer:
description = arcpy.Describe(input_layer)
try:
with arcpy.da.SearchCursor(input_layer, ['SHAPE@']) as search_cursor:
# Creating output feature class:
arcpy.CreateFeatureclass_management(
os.path.dirname(output_layer),
os.path.basename(output_layer),
geometry_type="POINT",
spatial_reference=description.spatialReference)
with arcpy.da.InsertCursor(output_layer, ['SHAPE@']) as insert_cursor:
for row in search_cursor:
line = row[0]
if line:
spaces_length = float(random.randint(0,int(line.length)))
for i in range(0, int(points_nb)):
insert_cursor.insertRow( [ line.positionAlongLine(spaces_length) ] )
spaces_length += float(random.randint(0,int(line.length)))
map.addDataFromPath(input_layer)
except arcpy.ExecuteError:
arcpy.AddError(arcpy.GetMessages())
Does anyone have any idea how to make it work properly?
for
loop inside yourif line
statement should not be there. It should be moved outside of yourtry
statement, perhaps. And you'll need to randomise the lines that are being chosen. Otherwise, it'll be the first five lines all the time. Perhaps try choosing 5 random lines and then create a point randomly on each one of them.