Create random points in a polygon

I needed to create random points inside polygons for some testing I needed to do. Since I only had a Standard Licence available (and therefore no access to the Create Random Points tool that I used to POST random points as ESRI JSON to a REST endpoint), I decided it was as good a time as any to write a tool in Python.

#
# @date 06/08/2015
# @author Cindy Williams
#
# Creates random points in each polygon feature
# without the need for an Advanced licence to run
# the Create Random Points tool.
#
# For use in the Python window in ArcCatalog.
#
import arcpy
import random
arcpy.env.workspace = r"C:\Some\Arb\Folder\work.gdb"
ftr_polys = "ftr_poly"
ftr_points = "ftr_points"
fields = ["SHAPE@", "Name"]
cursor_ins = arcpy.da.InsertCursor(ftr_points, fields)
with arcpy.da.SearchCursor(ftr_polys, fields) as cursor:
for row in cursor:
num_points = random.randint(1, 11)
poly_ext = [row[0].extent.XMin,
row[0].extent.XMax,
row[0].extent.YMin,
row[0].extent.YMax]
for n in xrange(num_points):
x = random.uniform(poly_ext[0], poly_ext[1])
y = random.uniform(poly_ext[2], poly_ext[3])
randpoint = [arcpy.PointGeometry(arcpy.Point(x, y)), row[1]]
cursor_ins.insertRow(randpoint)
del cursor_ins

After creating an InsertCursor on the point feature class, I iterate over the polygon feature class using a SearchCursor. In Line 25, a random number is chosen between 1 and 10 to determine the number of points that will be created for that feature. The extent of the current feature is stored in Line 26.

The actual points are created in Lines 30 – 34. For each point, a random floating point number within the polygon’s extent is chosen as the x and y coordinates. A point feature is created using the coordinates to build the geometry, as well as the name of the polygon feature. The point feature is then inserted into the point feature class.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.