def getXYArray(XYsStr): """ 通过coordinates解析出XY的数组 :param XYsStr: 格式"x,y;x,y;x,y..." :desc: 传入为gcj02坐标系坐标,返回wgs84坐标 :return: arr: 类型arcpy.array """ XYarray = arcpy.CreateObject("array") XYList = XYsStr.split(';') for XYstr in XYList: XY = XYstr.split(',') XY[0], XY[1] = float(XY[0]), float(XY[1]) point = arcpy.CreateObject("point") point.X, point.Y = coordinate_conversion.gcj02towgs84(XY[0], XY[1]) XYarray.add(point) return XYarray
def grid_create(self,out_Layer,gridshape,rastername,newfile,Mapdir,shape): """This function creates the maps for output. First it creates a new shapefile from the scored grids the user creates in SPM. Then the scored grids are interpolated using the IDW command. Next, rasters are applied to the Blank.mxd file provided in order to output JPEGS that are opened using the matplotlib.""" env.workspace = Mapdir self.SpRf = arcpy.Describe(shape).spatialReference arcpy.CreateFeatureclass_management(Mapdir,gridshape,"POINT", "","","",self.SpRf) arcpy.AddField_management(gridshape,"PROB","FLOAT") cursor = arcpy.InsertCursor(gridshape) df = DataFrame.from_csv(newfile) Xlocation = df.columns.get_loc("POINT_X") Ylocation = df.columns.get_loc("POINT_Y") probLoc = df.columns.get_loc("PROB_2") with open(newfile, 'rb') as csvfile: reader = csv.reader(csvfile) row = reader.next() for row in reader: Row = cursor.newRow() point = arcpy.CreateObject("Point") point.X, point.Y = float(row[Xlocation+1]), float(row[Ylocation+1]) Row.PROB = float(row[probLoc+1]) Row.shape = point cursor.insertRow(Row) del cursor
def txt_to_pnt(inTxt, pntShp, srs): """ Text file to Point Feature Class """ from glass.web.srorg import get_wkt_esri from glass.arcg.mng.featcls import create_feat_class # Create new feature class create_feat_class(pntShp, "POINT", get_wkt_esri(srs)) with open(inTxt, mode='r') as txt: cursor = arcpy.InsertCursor(pntShp) lines = txt.readlines() for line in lines: pnt = arcpy.CreateObject("Point") vals = line.split(" ") pnt.ID, pnt.X, pnt.Y = vals new_row = cursor.newRow() new_row.Shape = pnt cursor.insertRow(new_row) txt.close() return pntShp
def addNDVI(inputTif, workDir, outName): arcpy.CheckOutExtension('spatial') print "\nCalculating NDVI and stacking to band 5" red = arcpy.sa.Raster(os.path.join(inputTif, "Band_1")) NIR = arcpy.sa.Raster(os.path.join(inputTif, "Band_4")) numerator = arcpy.sa.Float(NIR - red) denominator = arcpy.sa.Float(NIR + red) NDVI = arcpy.sa.Divide(numerator, denominator) NDVI_times = arcpy.sa.Times(NDVI, 100) NDVI_add = arcpy.sa.Plus(NDVI_times, 100) NDVI_int = arcpy.sa.Int(NDVI_add) vtab = arcpy.CreateObject("ValueTable") vtab.addRow(os.path.join(inputTif, "Band_1")) vtab.addRow(os.path.join(inputTif, "Band_2")) vtab.addRow(os.path.join(inputTif, "Band_3")) vtab.addRow(os.path.join(inputTif, "Band_4")) vtab.addRow(NDVI_int) arcpy.CompositeBands_management( vtab, os.path.join(workDir, outName + '_RGBNIR_NDVI.tif')) arcpy.CheckInExtension('spatial') return os.path.join(workDir, outName + '_RGBNIR_NDVI.tif')
def TxtXYcoordinatesToPointArray(txtpath): #创建点用于存储X,Y坐标 pnt = arcpy.CreateObject("point") #创建点集 pntarray = arcpy.CreateObject("Array") fc = fileinput.input(txtpath) for line in fc: #分隔符设置 values = line.replace("\n", "").split("\t") #结束标志 if values[0] != "-END-": pnt.X,pnt.Y = values[0] , values[1] pntarray.add(pnt) fc.close() return pntarray
def zPoints2XSec(outName, Zpts, eventTable, ZField, ve, scratchDir): #creates 2d cross section view sticklogs that show the depth of each borehole try: # create the output featureclass #arcpy.CreateFeatureClass_management(scratchDir, outName, 'POLYLINE', Zboreholes, 'ENABLED', 'ENABLED') outFC = outName + '_idonly' arcpy.CreateFeatureClass_management(scratchDir, outFC, 'POINT', '#', 'ENABLED', 'ENABLED') # open search cursor on the event table tRows = arcpy.SearchCursor(eventTable) tRow = tRows.Next() # open insert cursor on the output layer cur = arcpy.InsertCursor(outFC) # create point and array objects pnt1 = arcpy.CreateObject('Point') arcpy.AddMessage('Placing points in cross-section view...') # enter while loop for each row in events table while tRow: # set the point's X and Y coordinates # set Y depending on whether the user wants to use the elevation of the # borehole from the specified Z value field. try: pnt1.y = float(tRow.GetValue(ZField)) * float(ve) except: arcpy.AddMessage('No elevation available for borehole OID ' + str(tRow.OBJECTID)) arcpy.AddMessage('Using a value of 5000') pnt1.y = 5000 pnt1.x = float(tRow.GetValue('RouteM')) # set array to the new feature's shape row = cur.newRow() row.shape = pnt1 # insert the feature cur.insertRow(row) # get the next row in the table tRow = tRows.Next() #join the output fc with the events table and transfer the attributes fInfo = 'OBJECTID OBJECTID HIDDEN; rkey rkey HIDDEN; RouteM RouteM HIDDEN' transferAtts(arcpy, outFC, eventTable, 'OBJECTID', 'OBJECTID', fInfo, outName) #arcpy.DeleteField(outName, 'rkey; RouteM; OBJECTID') except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = tbinfo + '\n' + str(sys.exc_type) + ': ' + str(sys.exc_value) arcpy.AddError(pymsg) raise SystemError
def CreateLine(a,b,shppath): firstpointx=(x1+a*y1-b*a)/(a*a+1) firstpointy=(a*x1+y1*a*a+b)/(a*a+1) lastpointx=(x2+a*y2-b*a)/(a*a+1) lastpointy=(a*x2+y2*a*a+b)/(a*a+1) pnt = arcpy.CreateObject("point") pntarray = arcpy.CreateObject("Array") pnt.X,pnt.Y=firstpointx,firstpointy pntarray.add(pnt) pnt.X,pnt.Y=lastpointx,lastpointy pntarray.add(pnt) polyline = arcpy.Polyline(pntarray) arcpy.CopyFeatures_management(polyline, shppath)
def xsecPoints(outFC, Zpts, eventTable, ZField): #shows the intersections between the cross-section line and other lines #in map view as points in cross-section view try: # create the output featureclass arcpy.CreateFeatureclass_management(scratchDir, outFC, 'POINT', Zpts, 'ENABLED', 'ENABLED') # open search cursor on the event table tRows = arcpy.SearchCursor(eventTable) # open insert cursor on the output layer cur = arcpy.InsertCursor(outFC) arcpy.AddMessage('Building points in cross-section view...') #get a list of fields in the template table that does not include OBJECTID or FID or SHAPE #anything else? add it to xf! ("excluded fields") xf = ('shape', 'objectid', 'fid', 'shape_length') lf = arcpy.ListFields(Zpts) names = [] for f in lf: if not f.name.lower() in xf: names.append(f.name) for tRow in tRows: #create point and array objects pnt = arcpy.CreateObject('Point') try: pnt.Y = float(tRow.getValue(ZField)) * float(ve) except: arcpy.AddMessage(' No elevation for feature ' + str(tRow.getValue('OBJECTID'))) arcpy.AddMessage(' Using a value of 0 for elevation') pnt.Y = 0 #set the point's X and Y coordinates pnt.X = float(tRow.getValue('RouteM')) #set the point to the new feature's shape row = cur.newRow() row.shape = pnt #copy over the other attributes for name in names: row.setValue(name, tRow.getValue(name)) #insert the feature cur.insertRow(row) except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = tbinfo + '\n' + str(sys.exc_type)+ ': ' + str(sys.exc_value) arcpy.AddError(pymsg) raise SystemError
def poi_cluster(poi_path, out_path): desc = arcpy.Describe(poi_path) shapeField = desc.ShapeFieldName rows = arcpy.SearchCursor(poi_path) level_types = [] out_data = [] for row in rows: #can't find a good way to get the unique value l = row.getValue('poilevelid') level_types.append(str(l)) level_types = set(level_types) max_flag = 0 #the range of the cluster for level_type in level_types: print(level_type) temp = 'poi' + level_type sql = '"poilevelid" = ' + level_type arcpy.MakeFeatureLayer_management(poi_path, temp) arcpy.SelectLayerByAttribute_management(temp, 'NEW_SELECTION', sql) scs = arcpy.SearchCursor(temp) data = [] #store the x and y level = [] #store the level of poi for sc in scs: shape = sc.getValue(shapeField) point = shape.getPart(0) l = sc.getValue('poilevelid') level.append(l) data.append([point.X, point.Y]) data = np.array(data, dtype=float) #DBSCAN to cluster C = dbscan(data, 0.001, 10) #100 Meters search radius for i in range(data.shape[0]): if C[i] >= 0: out_data.append( [data[i][0], data[i][1], C[i] + max_flag, level[i]]) max_flag = max_flag + max(C) + 1 #write the results sr = arcpy.SpatialReference(4326) fc = arcpy.CreateFeatureclass_management(workspace_path, out_path, "POINT", "", "", "", sr) arcpy.AddField_management(out_path, "cluster", "TEXT") arcpy.AddField_management(out_path, "poilevelid", "TEXT") cursor = arcpy.InsertCursor(fc) for i in range(len(out_data)): feature = cursor.newRow() vertex = arcpy.CreateObject("Point") vertex.X = out_data[i][0] vertex.Y = out_data[i][1] feature.shape = vertex # Add attributes feature.cluster = str(out_data[i][2]) feature.poilevelid = str(out_data[i][3]) # write to shapefile cursor.insertRow(feature) del cursor del fc
def trunkToFourLayerTif(inputTif, workDir, outName): print "\nTruncating alpha band" vtab = arcpy.CreateObject("ValueTable") vtab.addRow(os.path.join(inputTif, "Band_1")) vtab.addRow(os.path.join(inputTif, "Band_2")) vtab.addRow(os.path.join(inputTif, "Band_3")) vtab.addRow(os.path.join(inputTif, "Band_4")) arcpy.CompositeBands_management(vtab, os.path.join(workDir, 'fourComp.tif')) arcpy.Delete_management(inputTif) arcpy.Rename_management(os.path.join(workDir, 'fourComp.tif'), outName)
def create_shapefile(template_path, template_file, output_file, output_path, shp_output): # Set workspace env.workspace = output_path # Set local variables shp_file = output_path + 'template.shp' csv_file = output_path + output_file # Copy the shapefile template src_files = os.listdir(template_path) for file_name in src_files: full_file_name = os.path.join(template_path, file_name) if (os.path.isfile(full_file_name)): shutil.copy(full_file_name, output_path) # after https://gist.github.com/perrygeo/7220600 cursor = arcpy.InsertCursor(shp_file) with open(csv_file, 'rb') as f: reader = csv.DictReader(f) for row in reader: # Create the feature feature = cursor.newRow() # Eliminate samples outside the area of interest if float(row['long']) > -122.0 and \ float(row['long']) < -115.5 and \ float(row['lat']) > 44.0 and \ float(row['lat']) < 49.0: # Add the point geometry to the feature vertex = arcpy.CreateObject("Point") vertex.X = row['long'] vertex.Y = row['lat'] feature.shape = vertex # Add attributes feature.siteId = row['siteId'] feature.pedonKey = row['pedonKey'] feature.state = row['state'] feature.county = row['county'] feature.gcm2 = row['gcm2'] # write to shapefile cursor.insertRow(feature) # clean up del cursor # project from WGS84 to Albers coordinate_system = arcpy.SpatialReference( 'NAD 1983 Contiguous USA Albers') arcpy.Project_management(shp_file, shp_output, coordinate_system)
def PointToLine(txtpath,shppath): #创建用于存储X,Y坐标 pnt = arcpy.CreateObject("point") #创建点组 pntarray = arcpy.CreateObject("Array") #读取点坐标 fp=open(txtpath,"r") for line in fp.readlines(): lineArray=line.replace("\n","").split("\t") pnt.X,pnt.Y,pnt.Z = float(lineArray[0]),float(lineArray[1]),float(lineArray[2]) pntarray.add(pnt) fp.close() arcpy.env.overwriteOutput = True outPath,outFC=os.path.split(shppath) arcpy.CreateFeatureclass_management(outPath,outFC,"POINT","", "DISABLED","ENABLED") iCur=arcpy.InsertCursor(shppath) for i in pntarray: feat = iCur.newRow() feat.shape=i iCur.insertRow(feat) del iCur
def GPS_2shp(GPS_date, t_i): outputpath = "E:\\MapMatch\\GPS2shp\\201612%d"%(GPS_date) FCRef = "E:\\MapMatch\\shape_output\\20161219_001.shp" spatRef = arcpy.SpatialReference(4326) for i in range(t_i, t_i + 1): outputname = "GPS201612%d_%02d"%(GPS_date, i) e12_line = [] r_start = 48*i + 1 r_end = 48*(i + 1) for j in range(r_start, r_end + 1): inputfile = "D:\\项目资料\\深圳数据\\出租车GPS\\%d\\201612%d_%03d.txt"%(GPS_date, GPS_date, j) with open(inputfile, 'r') as file: for line in file: e12_line.append(line) print("201612%d_%03d.txt"%(GPS_date, j)) print(outputname) FC = arcpy.CreateFeatureclass_management(outputpath, outputname, "POINT", FCRef, "", "", spatRef) cursor = arcpy.InsertCursor(FC, ["Field1", "Field2", "sField3", "sField4", "Field5", "Field6", "Field7", "sField8", "sField9", "sField10"]) print(outputname + 'input_start') for oneline in e12_line: line = oneline.split(",") feature = cursor.newRow() vertex = arcpy.CreateObject("Point") vertex.X = line[4] vertex.Y = line[5] feature.shape = vertex feature.Field1 = line[0] feature.Field2 = line[1] feature.sField3 = line[2] feature.sField4 = line[3] feature.Field5 = line[4] feature.Field6 = line[5] feature.Field7 = line[6] feature.sField8 = line[7] feature.sField9 = line[8] feature.sField10 = line[9] cursor.insertRow(feature) print('Finish Projection:', outputname) del cursor del e12_line gc.collect()
def BoxOfPointsMaker(YourBoxOfPoints, XRange, YRange, meshsize=2000): '''This function makes a box of points given a shapefile, an xrange, a yrange and a meshsize. Default mesh size is 2000. When you run the function, your shapefile will be filled with a bunch of points shaped like a square defined by your x and y ranges. It is the most useful function of all time.''' cursorPnt = arcpy.da.InsertCursor(YourBoxOfPoints, ['SHAPE@']) xCoords = [] for j in range(int(xrange / meshsizes[i])): xCoords.append(Xmin + meshsizes[i] * j) ycoords = [] for j in range(int(yrange / meshsizes[i])): ycoords.append(Ymin + meshsizes[i] * j) point = arcpy.CreateObject('point') for g in range(len(xCoords)): point.X = xCoords[g] for g in range(len(ycoords)): point.Y = ycoords[g] cursorPnt.insertRow([point]) del cursorPnt
arcpy.env.workspace = 'C:\Users\jnordling\Dropbox\GEOG656\Lab8\lab8_data\WildlandFires.mdb' file_name = './lab8_data/NorthAmericaWildfires_2007275.txt' f = open(file_name, 'r') lstFires = f.readlines() count = 1 cur = arcpy.InsertCursor("FireIncidents") for fire in lstFires: if 'Latitude' in fire: continue else: values = fire.split(",") lat = float(values[0]) lng = float(values[1]) con = int(values[2]) pnt = arcpy.CreateObject("Point") pnt.X = lng pnt.Y = lat feat = cur.newRow() feat.shape = pnt feat.setValue("CONFIDENCEVALUE", con) cur.insertRow(feat) print 'Insert Complete! Total ' + str( count) + " points are inserted! " count = count + 1 del cur print 'Insert Complete! Total ' + str(count) + " points are inserted! " f.close()
def cluster_to_polygon(poi_cluster, out_path): desc = arcpy.Describe(poi_cluster) shapeField = desc.ShapeFieldName rows = arcpy.SearchCursor(poi_cluster) level_types = [] out_data = [] for row in rows: #can't find a good way to get the unique value l = row.getValue('poilevelid') level_types.append(str(l)) level_types = set(level_types) for level_type in level_types: temp_level = 'poi_cluster_' + level_type sql_level = '"poilevelid" = ' + "'" + level_type + "'" arcpy.MakeFeatureLayer_management(poi_cluster, temp_level) arcpy.SelectLayerByAttribute_management(temp_level, 'NEW_SELECTION', sql_level) scs = arcpy.SearchCursor(temp_level) cluster_types = [] for sc in scs: c = sc.getValue('cluster') cluster_types.append(str(c)) cluster_types = set(cluster_types) for cluster_type in cluster_types: temp_cluster = 'poi_cluster_' + level_type + '_' + cluster_type data = [] sql_cluster = '"poilevelid" = ' + "'" + level_type + "'" + ' AND ' + '"cluster" = ' + "'" + cluster_type + "'" print(sql_cluster) arcpy.MakeFeatureLayer_management(poi_cluster, temp_cluster) arcpy.SelectLayerByAttribute_management(temp_cluster, 'NEW_SELECTION', sql_cluster) scs = arcpy.SearchCursor(temp_cluster) for sc in scs: shape = sc.getValue(shapeField) point = shape.getPart(0) data.append([point.X, point.Y]) data = np.array(data, dtype=float) #2-d point [cen, rad] = cluster_centroid_radius(data) if (rad > 0): out_data.append([ cen[0], cen[1], rad * 1.5 * 10000, cluster_type, level_type ]) #rad*10000 to Meters print(level_type, cluster_type, cen[0], cen[1], rad) #write the results sr = arcpy.SpatialReference(4326) fc = arcpy.CreateFeatureclass_management(workspace_path, 'poi_test_cluster_cen.shp', "POINT", "", "", "", sr) arcpy.AddField_management('poi_test_cluster_cen.shp', "bufdis", "TEXT") arcpy.AddField_management('poi_test_cluster_cen.shp', "cluster", "TEXT") arcpy.AddField_management('poi_test_cluster_cen.shp', "poilevelid", "TEXT") cursor = arcpy.InsertCursor(fc) for i in range(len(out_data)): feature = cursor.newRow() vertex = arcpy.CreateObject("Point") vertex.X = out_data[i][0] vertex.Y = out_data[i][1] feature.shape = vertex # Add attributes feature.bufdis = str(out_data[i][2]) feature.cluster = str(out_data[i][3]) feature.poilevelid = str(out_data[i][4]) # write to shapefile cursor.insertRow(feature) del cursor del fc arcpy.Buffer_analysis('poi_test_cluster_cen.shp', out_path, 'bufdis') arcpy.Delete_management('poi_test_cluster_cen.shp')
def convertPointsToLine(inPts, outFeatures, IDField, cursorSort, close): try: # Assign empty values to cursor and row objects iCur, sRow, sCur, feat = None, None, None, None desc = arcpy.Describe(inPts) shapeName = desc.shapeFieldName # Create the output feature class # outPath, outFC = os.path.split(outFeatures) arcpy.CreateFeatureclass_management(outPath, outFC, "POLYLINE", "", enableParam(desc.hasM), enableParam(desc.hasZ), inPts) # If there is an IDField, add the equivalent to the output # if IDField: f = arcpy.ListFields(inPts, IDField)[0] tMap = { 'Integer': 'LONG', 'String': 'TEXT', 'SmallInteger': 'SHORT' } fType = f.type if tMap.has_key(fType): fType = tMap[fType] fName = arcpy.ValidateFieldName(f.name, outPath) arcpy.AddField_management(outFeatures, fName, fType, f.precision, f.scale, f.length, f.aliasName, f.isNullable, f.required, f.domain) # Open an insert cursor for the new feature class # iCur = arcpy.InsertCursor(outFeatures) sCur = arcpy.SearchCursor(inPts, "", None, cursorSort, cursorSort) sRow = sCur.Next() # Create an array and point object needed to create features # array = arcpy.CreateObject("Array") pt = arcpy.CreateObject("Point") # Initialize a variable for keeping track of a feature's ID. # ID = -1 while sRow: pt = sRow.getValue(shapeName).getPart(0) if IDField: currentValue = sRow.getValue(IDField) else: currentValue = None if ID == -1: ID = currentValue if ID <> currentValue: if array.count >= 2: # To close, add first point to the end # if close: array.add(array.getObject(0)) feat = iCur.newRow() if IDField: if ID: #in case the value is None/Null feat.setValue(IDField, ID) feat.setValue(shapeName, array) iCur.insertRow(feat) else: arcpy.AddIDMessage("WARNING", 1059, str(ID)) array.removeAll() array.add(pt) ID = currentValue sRow = sCur.next() # Add the last feature # if array.count > 1: # To close, add first point to the end # if close: array.add(array.getObject(0)) feat = iCur.newRow() if IDField: if ID: #in case the value is None/Null feat.setValue(IDField, currentValue) feat.setValue(shapeName, array) iCur.insertRow(feat) else: arcpy.AddIDMessage("WARNING", 1059, str(ID)) array.removeAll() except Exception as err: arcpy.AddError(err.message) finally: if iCur: del iCur if sRow: del sRow if sCur: del sCur if feat: del feat
def export_single_part(feapath , outpath, field, prename='', ishp = False): ''' feapath = r'w:\Platform\geodatabase\tools.gdb\tools\bnddb_clip' outpath = r'v:' prename = 'fd' export_single_part(feapath , outpath , prename) ''' # TODO: export attribute . field_names = [x.name for x in arcpy.ListFields(feapath)] try: field_names.remove('OBJECTID') field_names.remove('Shape') field_names.remove('ID') field_names.remove('Shape_Leng') field_names.remove('Shape_Length') field_names.remove('Shape_Area') except: pass print(field_names) arcpy.env.workspace = outpath polys = arcpy.SearchCursor(feapath) poly = polys.next() while poly: hao = str((poly.getValue(field))) feat = poly.shape a = 0 outfea = prename + hao if ishp : outfea = outfea + '.shp' # print(outfea) if arcpy.Exists(outfea): arcpy.Delete_management(outfea) # clear_feature(os.path.join(outpath, outfea)) # print('=' * 20) # print(outpath) # print(outfea) # print(feapath) arcpy.CreateFeatureclass_management(outpath , outfea, "Polygon", feapath) cur = arcpy.InsertCursor(outpath + os.sep + outfea ) lineArray = arcpy.CreateObject("Array") # pntout = gp.CreateObject("Point") polyArray = feat.getPart(a) pnt = polyArray.next() # print('::::::::::::::::::') while pnt: # print "; " + str(pnt.x) + "; " + str(pnt.y) # print(type(pnt)) # print(pnt) lineArray.add(pnt) pnt = polyArray.next() # print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<') feat = cur.newRow() # print(lineArray) feat.shape = lineArray # for fd_name in field_names: # feat.setValue(fd_name, poly.getValue(fd_name)) cur.insertRow(feat) lineArray.removeAll() del polyArray del pnt del feat poly = polys.next()
inputfile = "D:\\项目资料\\深圳数据\\出租车GPS\\合并\\20161219\\20161219_%03d.txt"%(j) #GPS数据输入 with open(inputfile, 'r') as file: for line in file: e12_line.append(line) #把每一行单独添加 #print("20161219_%03d.txt"%(j)) #print(outputname) FC = arcpy.CreateFeatureclass_management(outputpath, outputname, "POINT", FCRef, "", "", spatRef) #创建shp,这里创建文件! # CreateFeatureclass叫“创建要素类”,在文件夹中此工具将创建 shapefile。 cursor = arcpy.InsertCursor(FC, ["Field1", "Field2", "Field3", "Field4", "Field5", "Field6", "Field7", "Field8", "Field9", "Field10"]) #添加新的属性?@11/17 print(outputname + 'input_start') # for oneline in allLine: for oneline in e12_line: line = oneline.split(",") #取逗号为分隔符 newRow = cursor.newRow() #创建空行对象 vertex = arcpy.CreateObject("Point") vertex.X = line[4] #东经度 vertex.Y = line[5] #北维度 newRow.shape = vertex newRow.Field1 = line[0] newRow.Field2 = line[1] newRow.Field3 = line[2] newRow.Field4 = line[3] newRow.Field5 = line[4] newRow.Field6 = line[5] newRow.Field7 = line[6] newRow.Field8 = line[7] newRow.Field9 = line[8] newRow.Field10 = line[9] cursor.insertRow(newRow) #插入新行 print('Finish Projection:', outputname)
#get the offset for this profile #first, get the route key of this profile rte = profile.ORIG_FID if not rte == None: #and create a search cursor of hopefully just one row where the rkeys #in the profiles fc and the intersect table are the same where = '"rkey" = ' + str(rte) #rows = arcpy.SearchCursor(intersectTab, where) with arcpy.da.SearchCursor(intersectTab, "mValue", where) as rows: try: #get the offset distance #offset = rows.next().mValue offset = rows.next()[0] #create an empty container for the re-calced profile geometry newProf = arcpy.CreateObject('array') #get the existing geometry feat = profile.shape part = feat.getPart(0) for pnt in part: #recalc each x coordinate and add it to the new array object pnt.X = pnt.X - offset newProf.add(pnt) #compare Y values for the min and max of the dataset if pnt.Y > maxY: maxY = pnt.Y if pnt.Y < minY: minY = pnt.Y #set the old profile shape to the new and update
def CreatePoint(self, points): import arcpy vertex = arcpy.CreateObject("Point") vertex.X = points[1] vertex.Y = points[0] return vertex
def main(): try: # These are declaring input variables out_path = get_workspace() input_file = get_file() # This variable is being created as Global # Will be used in a function in another process global out_name out_name = get_out_name() arcpy.env.overwriteOutput = True # Set the arcpy workspace arcpy.env.workspace = out_path print ' ' # These variables are setting the parameters of the new feature called geometry_type = "POINT" spatial_reference = arcpy.Describe("FireIncidents").spatialReference template = arcpy.GetParameterAsText(2) # Templete #arcpy.AddWarning(template) has_m = "DISABLED" has_z = "DISABLED" # Creating the new feature #arcpy.CreateFeatureclass_management(out_path, out_name, geometry_type, template, has_m, has_z, spatial_reference) arcpy.CreateFeatureclass_management( os.path.split(out_name)[0], os.path.split(out_name)[1], "POINT", template) print 'Feature Class Create: ' + out_name # opening the file with the r for read only f = open(input_file, 'r') lstFires = f.readlines() count = 0 # This loop goes through each line of the file and inserts the headers as attribute fields # Then for all the other lines it will pars the latitude, longitude, confident level and # insert them into the new feature, as a point. for i in lstFires: if count == 0: # The first row of the file, creates the header and # Creates the Insert Cursor header = remove_new_line(i.split(",")) add_HeaderFields(header, template) rows = arcpy.InsertCursor(out_name) else: # gets the data into vaiables. and createing a point object line = remove_new_line(i.split(",")) lat = line[0] lng = line[1] cof = line[2] pnt = arcpy.CreateObject("Point") pnt.X = lng pnt.Y = lat # Inserting the data into the rows row = rows.newRow() # This creates the point feature row.shape = pnt # This if statement is to incert the right fields in the feature if len(header) == 4: row.setValue(str(header[0]), lat) row.setValue(str(header[1]), lng) row.setValue(str(header[3]), cof) else: row.setValue(str(header[0]), lat) row.setValue(str(header[1]), lng) row.setValue(str(header[2]), cof) rows.insertRow(row) print 'Insert Row Complete: ' + str(count) # Increasing the count count = count + 1 print "Insert Complete! Total " + str(count - 1) + " points are inserted!\n" del rows del row # Closes the open file f.close() except Exception, e: # Catching Errors it program fails print e print arcpy.GetMessages() arcpy.AddError(e)
def polygons_from_points(inputPnt, outputPol, prj, POLYGON_FIELD, ORDER_FIELD=None): """ Create a Polygon Table from a Point Table A given Point Table: FID | POLYGON_ID | ORDER_FIELD 0 | P1 | 1 1 | P1 | 2 2 | P1 | 3 3 | P1 | 4 4 | P2 | 1 5 | P2 | 2 6 | P2 | 3 7 | P2 | 4 Will be converted into a new Polygon Table: FID | POLYGON_ID 0 | P1 1 | P2 In the Point Table, the POLYGON_ID field identifies the Polygon of that point, the ORDER FIELD specifies the position (first point, second point, etc.) of the point in the polygon. If no ORDER field is specified, the points will be assigned to polygons by reading order. """ import os from glass.cpu.arcg.lyr import feat_lyr from glass.cpu.arcg.mng.featcls import create_feat_class from glass.cpu.arcg.mng.fld import add_field from glass.cpu.arcg.mng.fld import type_fields arcpy.env.overwriteOutput = True # TODO: Check Geometry of the Inputs # List all point pntLyr = feat_lyr(inputPnt) cursor = arcpy.SearchCursor(pntLyr) line = cursor.next() lPnt = {} cnt = 0 while line: # Get Point Geom pnt = line.Shape.centroid # Get Polygon Identification polygon = line.getValue(POLYGON_FIELD) # Get position in the polygon order = line.getValue(ORDER_FIELD) if ORDER_FIELD else cnt # Store data if polygon not in lPnt.keys(): lPnt[polygon] = {order: (pnt.X, pnt.Y)} else: lPnt[polygon].update({order: (pnt.X, pnt.Y)}) line = cursor.next() cnt += 1 del line del cursor # Write Output create_feat_class(outputPol, "POLYGON", prj) outLyr = feat_lyr(outputPol) # Add polygon ID fieldsPnt = type_fields(pntLyr) POLYGON_FIELD_TYPE = "TEXT" if fieldsPnt[POLYGON_FIELD] == 'String' \ else "SHORT" if fieldsPnt[POLYGON_FIELD] == 'Integer' else \ "TEXT" POLYGON_FIELD_PRECISION = 50 if POLYGON_FIELD_TYPE == "TEXT" else \ 15 add_field(outLyr, POLYGON_FIELD, POLYGON_FIELD_TYPE, POLYGON_FIELD_PRECISION) cursor = arcpy.InsertCursor(outLyr) # Add Polygons point = arcpy.CreateObject("Point") for polygon in lPnt: vector = arcpy.CreateObject("Array") pnt_order = lPnt[polygon].keys() pnt_order.sort() for p in pnt_order: point.ID = p point.X = lPnt[polygon][p][0] point.Y = lPnt[polygon][p][1] vector.add(point) # Add last point point.X = lPnt[polygon][pnt_order[0]][0] point.Y = lPnt[polygon][pnt_order[0]][1] vector.add(point) new_row = cursor.newRow() new_row.Shape = vector new_row.setValue(POLYGON_FIELD, str(polygon)) cursor.insertRow(new_row) vector = 0
arcpy.CreateFeatureclass_management( os.path.dirname(newFC), os.path.basename(newFC), "Polyline", "", "", "", "" ) # "r"F:\research\research_CMP\ADCIRC_codes\python\adcirc_grid_manning_projected2.shp") arcpy.AddField_management(newFC, "MeshID", "LONG") arcpy.AddField_management(newFC, "numele", "LONG") arcpy.AddField_management(newFC, "Node1", "LONG") arcpy.AddField_management(newFC, "Node2", "LONG") arcpy.AddField_management(newFC, "Node3", "LONG") # Describe the new feature class desc = arcpy.Describe(newFC) shpFld = desc.ShapeFieldName # Create point and cursor objects lineArray = arcpy.CreateObject("Array") pnt = arcpy.CreateObject("Point") cur = arcpy.InsertCursor(newFC) array = arcpy.CreateObject("Array") pnt = arcpy.CreateObject("Point") # Open the text file input = file(txtFile, "r") input.readline() line = input.readline() data = line.split() #print data nunnodes = int(data[1]) nunedges = int(data[0]) #nunnodes2 = 3
print "Creating the lists of x-y coordinate pairs." for i in range(len(CoordString2)): coords.append(CoordString2[i].split(',')) coords.pop(48) print "Creating a polyline feature class." #The feature class will be 'empty' at this point arcpy.CreateFeatureclass_management(env.workspace, 'line2.shp', 'POLYLINE') arcpy.AddField_management('line2.shp', 'numPnts', 'FLOAT') print "Creating a point object and an array object." #The point object will be used to create each of the vertices of the array arcpy.CreateFeatureclass_management(env.workspace, 'points.shp', 'POINT') point = arcpy.CreateObject('point') array = arcpy.CreateObject('array') Cursor = arcpy.da.InsertCursor('line2.shp', ['SHAPE@']) for i in range(len(coords)): point.X = coords[i][0] point.Y = coords[i][1] array.add(point) NumberofPoints = len(coords) arcpy.CalculateField_management('line2.shp', 'numPnts', str(NumberofPoints)) Polyline = arcpy.Polyline(array) Cursor.insertRow([Polyline]) del Cursor print "*******Part II********" print "Conducting 3D analysis"
##load node and way tags into fgdb ##-------------------------------------------------------------------------------- edit = arcpy.da.Editor(output) edit.startEditing(False, False) nodecursor = arcpy.da.InsertCursor(nodefc, nodefieldlist) waytagcursor = arcpy.da.InsertCursor(waytagtab, wayfieldlist) if loadNonstandardTags: othernodetagcursor = arcpy.da.InsertCursor( nodeothertag, ("Node_ID", "Tag_Name", "Tag_Value")) otherwaytagcursor = arcpy.da.InsertCursor( wayothertag, ("Way_ID", "Tag_Name", "Tag_Value")) nodepnt = arcpy.CreateObject("point") ftags = [] waystring = '' linecount = 0 blocknum = 1 nodefile = bz2.BZ2File(scratchSpace + '/nodeblock' + str(blocknum) + '.dat', 'w') switchval = blocksize * blocknum for uline in inputfile: #source should be in utf-8, but sometimes its not. #line=unicode(uline,"utf-8","replace") # Python3 requires str instead of unicode line = str(uline, "utf-8", "replace") element = getElement(line)
def boreholeLines(): #creates 2d cross section view sticklogs that show the depth of each borehole try: # create an empty output featureclass with the fields of the event table arcpy.CreateFeatureclass_management(scratchDir, bhLines, 'POLYLINE', zBoreholes, 'ENABLED', 'ENABLED') # open search cursor on the event table tRows = arcpy.SearchCursor(eventTable) # open insert cursor on the output layer cur = arcpy.InsertCursor(bhLines) # create point and array objects pnt1 = arcpy.CreateObject('Point') pnt2 = arcpy.CreateObject('Point') array = arcpy.CreateObject('Array') #get a list of fields in the template table that does not include OBJECTID or FID or SHAPE #anything else? add it to xf! ("excluded fields") xf = ('shape', 'objectid', 'fid', 'shape_length') lf = arcpy.ListFields(zBoreholes) names = [] for f in lf: if not f.name.lower() in xf: names.append(f.name) #we also want the 'DISTANCE' value, calculated when the event table is built #to be saved to this fc so it's needs to be in this list names.append('distance') # enter while loop for each row in events table for tRow in tRows: # set the point's X and Y coordinates # set Y depending on whether the user wants to use the elevation of the # borehole from the DEM or from a value in the collar z field try: pnt1.Y = float(tRow.getValue(zField)) * float(ve) except: arcpy.AddMessage( 'No collar elevation available for borehole ' + str(tRow.getValue(bhIdField))) arcpy.AddMessage('Using a value of 10000 for collar elevation') pnt1.Y = 10000 pnt1.X = tRow.RouteM pnt2.X = pnt1.X #if there is no value in bhDepthField, subtract 5000 from the top #elevation as a way of flagging this point try: pnt2.Y = pnt1.Y - (float( tRow.getValue(bhDepthField) * float(ve))) except: arcpy.AddMessage( ' No borehole depth available for borehole ' + str(tRow.getValue(bhIdField))) arcpy.AddMessage( ' Using a value of 5000 for borehole depth.') pnt2.Y = pnt1.Y - 5000 # add points to array array.add(pnt1) array.add(pnt2) # set array to the new feature's shape row = cur.newRow() row.shape = array # copy over the other attributes for name in names: #try to write the value, but maybe the field can't be found or the value can't be set #for some reason. Don't want the whole thing to blow up try: row.setValue(name, tRow.getValue(name)) except: #if it can't be written, forget about it pass # insert the feature cur.insertRow(row) #cleanup array.removeAll() except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = tbinfo + '\n' + str(sys.exc_type) + ': ' + str(sys.exc_value) arcpy.AddError(pymsg) raise SystemError
MeshEdges_shp = arcpy.GetParameterAsText(1) txtFile = arcpy.GetParameterAsText(0) MeshElements_shp = arcpy.GetParameterAsText(2) try: # Process: Feature To Polygon (Must change file path) arcpy.FeatureToPolygon_management(MeshEdges_shp, MeshElements_shp, "", "ATTRIBUTES", "") arcpy.AddField_management(MeshElements_shp, "Node1", "LONG") arcpy.AddField_management(MeshElements_shp, "Node2", "LONG") arcpy.AddField_management(MeshElements_shp, "Node3", "LONG") cur = arcpy.InsertCursor(MeshElements_shp) array = arcpy.CreateObject("Array") arcpy.AddMessage("Reading file...") input = file(txtFile, "r") input.readline() line = input.readline() data = line.split() #print data nunnodes = int(data[1]) nunedges = int(data[0]) print(nunedges) for num in range(nunnodes): line = input.readline() for num in range(0, nunedges): line = input.readline()
if shpType == 'Point': #open an update cursor on the copy rows = arcpy.da.UpdateCursor(layCopy, ["SHAPE@XY", "SHAPE@Z"]) for row in rows: #get the geometry of this point oldXY = row[0] oldX = oldXY[0] oldY = oldXY[1] #get the XY of this point based on the M value xDistance = oldX newXY = lerpXY(xDistance, vList, vDict) newX = newXY[0] newY = newXY[1] newPnt = arcpy.CreateObject('Point') arcpy.AddMessage('old :' + str(oldX) + ', ' + str(oldY)) arcpy.AddMessage('new :' + str(newXY[0]) + ', ' + str(newXY[1]) + ', ' + str(oldY / float(ve))) #write the coordinates to the new point #newX = newXY[0] #newY = newXY[1] newZ = (oldY / float(ve)) #update the row's shape row[0] = [newX, newY] row[1] = newZ rows.updateRow(row) else: #we're dealing with lines or polygons which are not so easy to edit
TableXY2Shape.py A script that reads the 'latitude' and 'longitude' fields in C:\Workspace\PNW\Edmonds\Geology\Edmonds.gdb\Geology\Boreholes, updates the geometry to those values, and re-writes the 'Easting' and 'Northing' fields. """ import arcpy #fc = r'C:\Documents and Settings\ethoms\My Documents\ArcGIS\Default.gdb\Export_Output' fc = r'C:\Workspace\PNW\Edmonds\Geology\Edmonds.gdb\Geology\Boreholes' WGS84 = arcpy.CreateSpatialReference_management( r'C:\ArcGIS\Desktop10.0\Coordinate Systems\Geographic Coordinate Systems\World\WGS 1984.prj' ) rows = arcpy.UpdateCursor(fc, '', WGS84) for row in rows: if row.Longitude: lon = row.Longitude lat = row.Latitude pt = arcpy.CreateObject('point') pt.X = lon pt.Y = lat row.Shape = pt rows.updateRow(row) print row.Shape.getPart().X, row.Shape.getPart().Y row.Easting = row.Shape.getPart().X row.Northing = row.Shape.getPart().Y rows.updateRow(row)