HOW TO

Generate random polygons in a specified region using ArcPy in ArcGIS Pro

Last Published: November 21, 2024

Summary

In ArcGIS Pro, creating random polygons within a specified area can be useful for various purposes, particularly in spatial analysis and environmental modeling. For example, random polygons allow for spatial sampling within a study area. This is essential in fields such as ecology and urban planning where sample plots or test sites across different locations are required to model environmental impacts, assess vegetation, or simulate potential urban development patterns.

This article describes the workflow to generate random polygons in a specified region 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 following script.
    1. Import the necessary modules.
import arcpy
import random
  1. Set the environment settings.
arcpy.env.overwriteOutput = True
  1. Define the parameters.
output_location = r"C:\path\to\geodatabase.gdb"  # Update with the geodatabase path
polygon_name = "<nameOfPolygon>"  # Name for the polygon feature class
num_polygons = <number>  # Number of random street-like polygons to generate
  1. Define the bounding box coordinates for the specific location. In this example, the coordinates for Redlands, California is specified.
min_x, min_y = -117.207, 34.025  # Southwest corner
max_x, max_y = -117.165, 34.050  # Northeast corner
  1. Define the spatial reference.
spatial_reference = arcpy.SpatialReference(4326)  # SRID 4326 for geographic coordinates
  1. Create a new feature class for the polygons with a defined spatial reference.
arcpy.CreateFeatureclass_management(output_location, polygon_name, "POLYGON", spatial_reference=spatial_reference)
  1. Add a field for street names. Replace StreetName with the field name.
arcpy.AddField_management(f"{output_location}/{polygon_name}", "StreetName", "TEXT")
  1. Create a function to check overlaps of new polygons with existing polygons.
def check_overlap(new_polygon, existing_polygons):
    for poly in existing_polygons:
        if new_polygon.overlaps(poly) or new_polygon.crosses(poly):
            return True
    return False
  1. Generate random street-like polygons within the defined bounding box.
with arcpy.da.InsertCursor(f"{output_location}/{polygon_name}", ["SHAPE@", "StreetName"]) as cursor:
    existing_polygons = []
    for i in range(num_polygons):
        while True:
            # Randomly select the center point for the polygon
            center_x = random.uniform(min_x, max_x)
            center_y = random.uniform(min_y, max_y)

            # Generate a polygon with random vertex points
            num_vertices = random.randint(3, 6)  # Number of vertices for the polygon
            angle_step = 360 / num_vertices  # Angle between vertices

            # Create an array to hold the polygon points
            polygon_points = arcpy.Array()

            for j in range(num_vertices):
                angle = angle_step * j  # Calculate the angle for the current vertex
                distance = random.uniform(0.002, 0.005)  # Random distance from the center
                vertex_x = center_x + distance * random.choice([-1, 1])  # Randomly offset x
                vertex_y = center_y + distance * random.choice([-1, 1])  # Randomly offset y

            # Append the point to the array
                polygon_points.add(arcpy.Point(vertex_x, vertex_y))

            # Close the polygon by adding the first point again
            polygon_points.add(polygon_points.getObject(0))

            # Create the polygon geometry
            new_polygon = arcpy.Polygon(polygon_points)

            # Check for overlap
            if not check_overlap(new_polygon, existing_polygons):
                # Insert the new polygon into the feature class
                cursor.insertRow([new_polygon, f"StreetPolygon_{i + 1}"])
                existing_polygons.append(new_polygon)  # Add to existing polygons
                break  # Exit the while loop
  1. Print the message when the polygons are generated successfully.
print("Random street-like polygons generated successfully in Redlands, CA.")

The code block below demonstrates the full working script.

import arcpy
import random

arcpy.env.overwriteOutput = True

output_location = r"C:\Users\Documents\ArcGIS\Projects\MyProject42\MyProject42.gdb"
polygon_name = "RedlandsStreetPolygons"
num_polygons = 100

min_x, min_y = -117.207, 34.025
max_x, max_y = -117.165, 34.050

spatial_reference = arcpy.SpatialReference(4326)

arcpy.CreateFeatureclass_management(output_location, polygon_name, "POLYGON", spatial_reference=spatial_reference)

arcpy.AddField_management(f"{output_location}/{polygon_name}", "StreetName", "TEXT")

def check_overlap(new_polygon, existing_polygons):
    for poly in existing_polygons:
        if new_polygon.overlaps(poly) or new_polygon.crosses(poly):
            return True
    return False

with arcpy.da.InsertCursor(f"{output_location}/{polygon_name}", ["SHAPE@", "StreetName"]) as cursor:
    existing_polygons = []
    for i in range(num_polygons):
        while True:
            center_x = random.uniform(min_x, max_x)
            center_y = random.uniform(min_y, max_y)

            num_vertices = random.randint(3, 6)
            angle_step = 360 / num_vertices

            polygon_points = arcpy.Array()

            for j in range(num_vertices):
                angle = angle_step * j
                distance = random.uniform(0.002, 0.005)
                vertex_x = center_x + distance * random.choice([-1, 1])
                vertex_y = center_y + distance * random.choice([-1, 1])

                polygon_points.add(arcpy.Point(vertex_x, vertex_y))

            polygon_points.add(polygon_points.getObject(0))

            new_polygon = arcpy.Polygon(polygon_points)

            if not check_overlap(new_polygon, existing_polygons):
                cursor.insertRow([new_polygon, f"StreetPolygon_{i + 1}"])
                existing_polygons.append(new_polygon)
                break

print("Random street-like polygons generated successfully in Redlands, CA.")

The map shows the random polygons generated.

Random polygons are generated in Redlands, California

Article ID: 000034065

Software:
  • ArcGIS Pro 3 1
  • ArcGIS Pro 3 3
  • ArcGIS Pro 3 2

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