importos,sysimportogrfrommathimportceildefmain(outputGridfn,xmin,xmax,ymin,ymax,gridHeight,gridWidth):# convert sys.argv to floatxmin=float(xmin)xmax=float(xmax)ymin=float(ymin)ymax=float(ymax)gridWidth=float(gridWidth)gridHeight=float(gridHeight)# get rowsrows=ceil((ymax-ymin)/gridHeight)# get columnscols=ceil((xmax-xmin)/gridWidth)# start grid cell enveloperingXleftOrigin=xmin
ringXrightOrigin=xmin+gridWidth
ringYtopOrigin=ymax
ringYbottomOrigin=ymax-gridHeight# create output fileoutDriver=ogr.GetDriverByName('ESRI Shapefile')ifos.path.exists(outputGridfn):os.remove(outputGridfn)outDataSource=outDriver.CreateDataSource(outputGridfn)outLayer=outDataSource.CreateLayer(outputGridfn,geom_type=ogr.wkbPolygon)featureDefn=outLayer.GetLayerDefn()# create grid cellscountcols=0whilecountcols
ringYbottom=ringYbottomOrigin
countrows=0whilecountrows
ringYbottom=ringYbottom-gridHeight# new envelope for next polyringXleftOrigin=ringXleftOrigin+gridWidth
ringXrightOrigin=ringXrightOrigin+gridWidth# Close DataSourcesoutDataSource.Destroy()if__name__=="__main__":## example run : $ python grid.py .shp xmin xmax ymin ymax gridHeight gridWidth#iflen(sys.argv)!=8:print"[ ERROR ] you must supply seven arguments: output-shapefile-name.shp xmin xmax ymin ymax gridHeight gridWidth"sys.exit(1)main(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4],sys.argv[5],sys.argv[6],sys.argv[7])