Grid inside polygon

1345
3
08-30-2017 01:58 AM
PaulinaR
New Contributor

I am trying to create a grid inside polygon. I applied a fishnet solution. Nevertheless, when I run the code the polygon is expanding (see attached photos). Could you point me what I am doing wrong? I am using the code that I have found in one of discussions. I have changed many things, but maybe I have omitted something important. Many thanks for help!

class NetButton(object):
    """Implementation for NetButton.button (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False
    def onClick(self):
        in_polys= ExcavationZone #established earlier as global
        out_loc= "\\\\abc\\home\\xxx\\Documents\\moje dokumenty\\xyz\\arcgis" #final grid 
        cell_x= 0
        cell_y= 0
        n_rows= 30
        n_cols= 30
    

        # Create file gdb to store data
        gdb = str(arcpy.CreateFileGDB_management(out_loc, 'Fishnets.gdb').getOutput(0))

        # spatial reference
        arcpy.env.outputCoordinateSystem = arcpy.Describe(in_polys).spatialReference
    
        # Loop thru rows of input polygons
        with arcpy.da.SearchCursor(in_polys, ['SHAPE@', 'OID@']) as rows:
            for row in rows:
                ext = row[0].extent
                st = '%f %f' %(ext.XMin, ext.YMin)
                orien = '%f %f' %(ext.XMin, ext.YMax)

                # Create fishnet
                out = os.path.join(gdb, 'fish_{0}'.format(row[1]))
                arcpy.CreateFishnet_management(out, st, orien, cell_x,
                                           cell_y, n_rows, n_cols,
                                           labels='NO_LABELS',
                                           geometry_type='POLYGON')

        # set workspace to new gdb
        arcpy.env.workspace = gdb
        fishnets = arcpy.ListFeatureClasses()
        targ = fishnets[0]
        for i, fish in enumerate(fishnets):
        
            # Add field for original polygon ID
            fid = fish.split('_')[1]
            arcpy.AddField_management(fish, 'POLY_ID', 'LONG')
            with arcpy.da.UpdateCursor(fish, ['POLY_ID']) as rows:
                for row in rows:
                    row[0] = fid
                    rows.updateRow(row)

            # append fishnets into one feature class
            if i > 0:
                arcpy.Append_management([fish], targ, 'NO_TEST')
                arcpy.Delete_management(fish)
                print 'Appended: {0}'.format(fish)

        print 'Done'
        return

        if __name__ == '__main__':

            polys = "\\\\abc\\home\\xxx\\Documents\\moje dokumenty\\abc\\arcgis\\PolygonGrid"  
            loc = "\\\\abc\\home\\xxx\\Documents\\moje dokumenty\\abc\\arcgis"  
    
        CreateFishnetsForFeats(polys, loc, 100, 100, 22, 22)
0 Kudos
3 Replies
JayantaPoddar
MVP Esteemed Contributor

Ensure you are using a Projected Coordinate System for the input (and output) Feature Class with appropriate linear units (Meters/Feet).



Think Location
0 Kudos
RebeccaStrauch__GISP
MVP Esteemed Contributor

The "polygon" option does not necessarily limit within the polygon, but will make the output polygons (i.e. grid cells) vs. lines.  (Try clipping if if you need that, but that may not b what you were asking)

geometry_type (Optional):

Determines if the output fishnet cells will be polyline or polygon features.

  • POLYLINE —Output is a polyline feature class. Each cell is defined by four line features.
  • POLYGON —Output is a polygon feature class. Each cell is defined by one polygon feature.

But as Jayanta Poddar‌ mention, it probably has something to do with the coordinate you are providing not being the same as the coordinates of the Feature Class.

I would review the help

Create Fishnet—Help | ArcGIS Desktop

How Create Fishnet works—Help | ArcGIS Desktop

and especially take note of this

Note:

The order of the parameters in the tool dialog box is different than the order of the parameters in the Python syntax.

If you have problems, it is always best to try it manually first using the tool, then you can see what the issue may be, and right-click the results to capture the python snippet...but the note above will be important when you go back to your tool.

0 Kudos
PaulinaR
New Contributor

Hi!

Thank you all for answers. Meanwhile I tried a little bit different approach. Because my next step is to create raster and assign values to it ( I want to create a risk map) I decided to first create an extent. Nevertheless, I don't know if it is a good approach, thus I will appreciate your suggestions and feedback in case you disagree with my idea. I was thinking that maybe Minimum Bounding Geometry would be better but I am not sure of that...

My code for creating an extent:

class NetButton(object):
    """Implementation for NetButton.button (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False
    def onClick(self):
        fc = ExcavationZone
        ExtentOutput="\\\\abc\\home\\xxx\\Documents\\moje dokumenty\\xyz\\arcgis\\ExtentOutput"
        mxd = arcpy.mapping.MapDocument ("CURRENT")
        sr = mxd.activeDataFrame.spatialReference
        desc = arcpy.Describe(fc)
        extent = desc.extent
        pts = [arcpy.Point(extent.XMin, extent.YMin),
            arcpy.Point(extent.XMax, extent.YMin),
            arcpy.Point(extent.XMax, extent.YMax),
            arcpy.Point(extent.XMin, extent.YMax)]
        #print extent.XMin,extent.YMin,extent.XMax,extent.YMax
        print ("XMax:",extent.XMax,"YMax:",extent.YMax)
        print ("XMin:",extent.XMin,"YMin:",extent.YMin)
        print ("XMax:",extent.XMax,"YMax:",extent.YMin)
        print ("XMax:",extent.XMin,"YMax:",extent.YMax)
        array = arcpy.Array(pts)
        poly = arcpy.Polygon(array,sr)
        #New shapefile 
        if arcpy.Exists(ExtentOutput):  
            arcpy.Append_management(poly, ExtentOutput)  
        else:  
            arcpy.CopyFeatures_management(poly, ExtentOutput)  
        print "Done!"
0 Kudos