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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|# @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.|
|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.extent.XMin,|
|for n in xrange(num_points):|
|x = random.uniform(poly_ext, poly_ext)|
|y = random.uniform(poly_ext, poly_ext)|
|randpoint = [arcpy.PointGeometry(arcpy.Point(x, y)), row]|
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
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.