# 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.extent.XMin, row.extent.XMax, row.extent.YMin, row.extent.YMax] 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] 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.

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