HOW TO

Generate randomly angled lines using ArcPy in ArcGIS Pro

Last Published: December 10, 2024

Summary

In ArcGIS Pro, randomly angled lines can be generated at a specific location on the map. This is useful in environmental studies where randomly angled lines can simulate transects for wildlife surveys. This ensures unbiased sampling across varied terrains, providing accurate data for habitat analysis and conservation planning.

This article describes the workflow to generate randomly angled lines using ArcPy in ArcGIS Pro.

Procedure

Note: 
This workflow requires the full script to run in the ArcGIS Pro Python window.
  1. Open the project in ArcGIS Pro.
  2. Open the Python window. Refer to ArcGIS Pro: Python window for more information.
  3. Run the script below.
    1. To import the necessary modules:
import arcpy
import random
import math
    1. To define the output feature class and spatial reference:
output_fc = r"C:\path\to\the\geodatabase.gdb\RandomLines"  # Change to the output feature class path.
spatial_reference = arcpy.SpatialReference(4326)  # WGS 84, or change to match the map’s coordinate system.
    1. To specify the extent to which the lines can be generated:
extent = arcpy.Extent(-117.2, 34.05, -117.15, 34.1)  # Adjust the coordinates as needed.
    1. To set the number of random lines to generate; in this example, it is set to 10.
num_lines = 10
    1. To set the minimum and maximum lengths of the lines:
min_length = 0.01
max_length = 0.02
    1. To set the randomness of the angles:
min_angle = 0
max_angle = 360
    1. To create a new feature class if required and add fields to store the line properties:
try:
    if not arcpy.Exists(output_fc):
        arcpy.CreateFeatureclass_management(out_path=arcpy.Describe(output_fc).path,
                                            out_name=arcpy.Describe(output_fc).name,
                                            geometry_type="POLYLINE",
                                            spatial_reference=spatial_reference)
        print("Feature class created at: {}".format(output_fc))
    else:
        print("Feature class already exists.")

    arcpy.AddField_management(output_fc, "LineID", "LONG")
    print("Field 'LineID' added.")

except arcpy.ExecuteError:
    print("Error during feature class creation or field addition.")
    print(arcpy.GetMessages())
    1. To create the insert cursor to add the random lines to the feature class:
try:
    with arcpy.da.InsertCursor(output_fc, ["SHAPE@", "LineID"]) as cursor:
      for line_id in range(1, num_lines + 1):
            x_start = random.uniform(extent.XMin, extent.XMax)
            y_start = random.uniform(extent.YMin, extent.YMax)
    1. To generate a random angle between the minimum and maximum angles:
            angle = random.uniform(min_angle, max_angle)
          length = random.uniform(min_length, max_length)
    1. To calculate the endpoint of the lines using trigonometric functions:
            x_end = x_start + length * math.cos(math.radians(angle))
            y_end = y_start + length * math.sin(math.radians(angle))
    1. To create the line geometry and insert it into the feature class:
            array = arcpy.Array([arcpy.Point(x_start, y_start), arcpy.Point(x_end, y_end)])
            polyline = arcpy.Polyline(array, spatial_reference)
            cursor.insertRow([polyline, line_id])
    1. To print the output progress after each line is added:
print("Line {} created: Start({}, {}) -> End({}, {})".format(line_id, x_start, y_start, x_end, y_end))

    print("All random lines have been successfully added to the feature class.")

except arcpy.ExecuteError:
    print("Error during line creation or insertion.")
    print(arcpy.GetMessages())
    1. To add the feature class to the current map and zoom to the new lines:
try:
    aprx = arcpy.mp.ArcGISProject("CURRENT")
  map_obj = aprx.listMaps()[0]
  layer = map_obj.addDataFromPath(output_fc)

    map_obj.defaultView.zoomToLayer(layer)
    print("Feature class added to the map and zoomed in.")

except Exception as e:
    print("Error adding layer to map or zooming in.")
    print(str(e))
    1. To print a message after running the script to indicate it is complete:
print("Script finished. Randomly angled lines created and displayed.")

The code block below demonstrates the full working script.

import arcpy
import random
import math

output_fc = r"C:\Users\Documents\ArcGIS\Projects\MyProject42\MyProject42.gdb\RandomLines"  # Change to the output feature class path.
spatial_reference = arcpy.SpatialReference(4326)  # WGS 84, or change to match the map’s coordinate system.

extent = arcpy.Extent(-117.2, 34.05, -117.15, 34.1)  # Adjust coordinates as needed (Redlands, CA)

num_lines = 10

min_length = 0.01
max_length = 0.02

min_angle = 0
max_angle = 360

try:
    if not arcpy.Exists(output_fc):
        arcpy.CreateFeatureclass_management(out_path=arcpy.Describe(output_fc).path,
                                            out_name=arcpy.Describe(output_fc).name,
                                            geometry_type="POLYLINE",
                                            spatial_reference=spatial_reference)
        print("Feature class created at: {}".format(output_fc))
    else:
        print("Feature class already exists.")

    arcpy.AddField_management(output_fc, "LineID", "LONG")
    print("Field 'LineID' added.")

except arcpy.ExecuteError:
    print("Error during feature class creation or field addition.")
    print(arcpy.GetMessages())

try:
    with arcpy.da.InsertCursor(output_fc, ["SHAPE@", "LineID"]) as cursor:
      for line_id in range(1, num_lines + 1):
            x_start = random.uniform(extent.XMin, extent.XMax)
            y_start = random.uniform(extent.YMin, extent.YMax)

          angle = random.uniform(min_angle, max_angle)
          length = random.uniform(min_length, max_length)

            x_end = x_start + length * math.cos(math.radians(angle))
            y_end = y_start + length * math.sin(math.radians(angle))

            array = arcpy.Array([arcpy.Point(x_start, y_start), arcpy.Point(x_end, y_end)])
            polyline = arcpy.Polyline(array, spatial_reference)
            cursor.insertRow([polyline, line_id])

            print("Line {} created: Start({}, {}) -> End({}, {})".format(line_id, x_start, y_start, x_end, y_end))

    print("All random lines have been successfully added to the feature class.")

except arcpy.ExecuteError:
    print("Error during line creation or insertion.")
    print(arcpy.GetMessages())

try:
    aprx = arcpy.mp.ArcGISProject("CURRENT")
  map_obj = aprx.listMaps()[0]
  layer = map_obj.addDataFromPath(output_fc)

    map_obj.defaultView.zoomToLayer(layer)
    print("Feature class added to the map and zoomed in.")

except Exception as e:
    print("Error adding layer to map or zooming in.")
    print(str(e))

print("Script finished. Randomly angled lines created and displayed.")

The map below shows the random lines generated at random angles.

The random lines are generated at random angles

Article ID: 000034192

Software:
  • ArcGIS Pro 3 3
  • ArcGIS Pro 3 2
  • ArcGIS Pro 3 4

Receive notifications and find solutions for new or common issues

Get summarized answers and video solutions from our new AI chatbot.

Download the Esri Support App

Related Information

Discover more on this topic

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options