def addNotation(notationType, fieldsToAdd, joinFieldName, outputTable, scratchTable, inputXField, inputYField, inputCoordinateFormat, inputSpatialReference): ''' ''' try: arcpy.AddMessage( "Converting & appending {0} with fields {1} ...".format( notationType, fieldsToAdd)) arcpy.ConvertCoordinateNotation_management(outputTable, scratchTable, inputXField, inputYField, inputCoordinateFormat, notationType, joinFieldName, inputSpatialReference) arcpy.JoinField_management(outputTable, joinFieldName, scratchTable, joinFieldName, fieldsToAdd) # TRICKY DDLat, DDLon names are hard-coded in ConvertCoordinateNotation so # We need to rename one of these to have both DD and DD_NUMERIC in same output table if notationType == 'DD_NUMERIC': arcpy.AlterField_management(outputTable, 'DDLat', 'DDLatNumeric', 'DDLatNumeric') arcpy.AlterField_management(outputTable, 'DDLon', 'DDLonNumeric', 'DDLonNumeric') return True except arcpy.ExecuteError: error = True # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) #print msgs #UPDATE print(msgs)
def stateCreatePoints(x, y, z): input_table = x + "/" + y + '_' + z + '.csv' output_points = y + "_" + z + ".gdb/" + y + '_' + z x_field = columnLon y_field = columnLat input_format = 'DD_2' output_format = 'DD_2' id_field = '' spatial_ref = arcpy.SpatialReference('WGS 1984') arcpy.ConvertCoordinateNotation_management(input_table, output_points, x_field, y_field, input_format, output_format, id_field, spatial_ref)
def createPoints(workarea, gdbname, csvname, fcname, latfield, longfield): input_table = workarea + "/" + csvname + '.csv' output_points = gdbname + ".gdb/" + fcname x_field = longfield y_field = latfield input_format = 'DD_2' output_format = 'DD_2' id_field = '' spatial_ref = arcpy.SpatialReference('WGS 1984') arcpy.ConvertCoordinateNotation_management(input_table, output_points, x_field, y_field, input_format, output_format, id_field, spatial_ref) print 'Point feature class created'
def nationalCreatePoints(x, y, z, w): # (tempFolder,stateX,projectFolder,csvName) input_table = x + "/" + y + '.csv' output_points = z + "/" + w + "_National.gdb/" + y x_field = columnLon y_field = columnLat input_format = 'DD_2' output_format = 'DD_2' id_field = '' spatial_ref = arcpy.SpatialReference('WGS 1984') arcpy.ConvertCoordinateNotation_management(input_table, output_points, x_field, y_field, input_format, output_format, id_field, spatial_ref)
def PRE(): global x_field, y_field, input_format, output_format, id_field, spatial_ref, in_coor_system des = "E:/Project/PRE.gdb/" location = "E:/Project/PRE/" dirs = os.listdir(location) for file in tqdm(dirs): name = location + file new_file = file.rstrip('.csv') final = des + new_file input_table = name output_points = final arcpy.ConvertCoordinateNotation_management(input_table, output_points, x_field, y_field, input_format, output_format, id_field, spatial_ref, in_coor_system)
def ETo(): ## Convert csvs to points data in ArcGIS database. Database should be CREATED BEFORE global x_field, y_field, input_format, output_format, id_field, spatial_ref, in_coor_system des = "E:/Project/ETo.gdb/" location = "E:/Project/ETo/" dirs = os.listdir(location) for file in tqdm(dirs): name = location + file new_file = file.rstrip('.csv') final = des + new_file input_table = name output_points = final arcpy.ConvertCoordinateNotation_management(input_table, output_points, x_field, y_field, input_format, output_format, id_field, spatial_ref, in_coor_system)
def projection(kind): # Project points into map global x_field, y_field, input_format, output_format, id_field, spatial_ref, in_coor_system if doOverWrite: reconstruct(kind) des = path + kind + ".gdb\\" location = path + kind + "\\" dirs = os.listdir(location) for file in dirs: name = location + file new_file = file.rstrip('.csv') final = des + new_file input_table = name output_points = final arcpy.ConvertCoordinateNotation_management(input_table, output_points, x_field, y_field, input_format, output_format, id_field, spatial_ref, in_coor_system)
def addNotation(notationType, fieldsToAdd, joinFieldName, outputTable, scratchTable): ''' ''' try: arcpy.AddMessage( "Converting & appending {0} with fields {1} ...".format( notationType, fieldsToAdd)) arcpy.ConvertCoordinateNotation_management(outputTable, scratchTable, inputXField, inputYField, inputCoordinateFormat, notationType, joinFieldName, inputSpatialReference) arcpy.JoinField_management(outputTable, joinFieldName, scratchTable, joinFieldName, fieldsToAdd) return True except arcpy.ExecuteError: error = True # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) #print msgs #UPDATE print(msgs)
coordinate2=arcpy.SpatialReference(4326) # Generate UTM coordinates output=arcpy.AddGeometryAttributes_management(in_features, properties, length_unit, area_unit, coordinate1) # Rename the field ## As field names are overwriten every time different coordinates are added, we need to ## change the field names: fieldNames = [f.name for f in arcpy.ListFields(output)] if "X" in fieldNames: print("") else: output=arcpy.AlterField_management(output, 'POINT_X', 'X', '') output=arcpy.AlterField_management(output, 'POINT_Y', 'Y', '') # Generate lat and long output1=arcpy.AddGeometryAttributes_management(output, properties, length_unit, area_unit, coordinate2) #arcpy.CopyFeatures_management(output1, in_features+"_TEST") # Add different coordinate format from the above table x_field="POINT_X" y_field="POINT_Y" input_coordinate="DD_2" output_coordinate="DD_1" #out_pts = "C:/Users/oc3512/Documents/ArcGIS/Projects/MMSP/MMSP_utm.gdb/MMSP_Stations_utm333" out_pts=arcpy.GetParameterAsText(1) # output: feature class arcpy.ConvertCoordinateNotation_management(output1, out_pts, x_field, y_field, input_coordinate, output_coordinate)
scratchTable = os.path.join(scratchWS,"cc_temp") delete_me.append(scratchTable) # Local variables: intermed = Output_Table # Process: Copy Rows arcpy.CopyRows_management(Input_Table, Output_Table, "") # Process: Add Unique Row ID arcpy.AddUniqueRowID_InC(Output_Table, "JoinID") # Process: Convert Coordinate Notation (GARS) arcpy.AddMessage("Converting & appending GARS ...") arcpy.ConvertCoordinateNotation_management(intermed, scratchTable, X_Field__Longitude__UTM__MGRS__USNG__GARS__GeoRef_, Y_Field__Latitude_, Input_Coordinate_Format, "GARS", "JoinID", Spatial_Reference) arcpy.JoinField_management(intermed, "JoinID", scratchTable, "JoinID", "GARS") # Process: Convert Coordinate Notation (DD) arcpy.AddMessage("Converting & appending Decimal Degrees ...") arcpy.ConvertCoordinateNotation_management(intermed, scratchTable, X_Field__Longitude__UTM__MGRS__USNG__GARS__GeoRef_, Y_Field__Latitude_, Input_Coordinate_Format, "DD", "JoinID", Spatial_Reference) arcpy.JoinField_management(intermed, "JoinID", scratchTable, "JoinID", "DDLat;DDLon") # Process: Convert Coordinate Notation (DDM) arcpy.AddMessage("Converting & appending Degrees Decimal Minutes ...") arcpy.ConvertCoordinateNotation_management(intermed, scratchTable, X_Field__Longitude__UTM__MGRS__USNG__GARS__GeoRef_, Y_Field__Latitude_, Input_Coordinate_Format, "DDM", "JoinID", Spatial_Reference) arcpy.JoinField_management(intermed, "JoinID", scratchTable, "JoinID", "DDMLat;DDMLon") # Process: Convert Coordinate Notation (DMS) arcpy.AddMessage("Converting & appending Degrees Minutes Seconds ...") arcpy.ConvertCoordinateNotation_management(intermed, scratchTable, X_Field__Longitude__UTM__MGRS__USNG__GARS__GeoRef_, Y_Field__Latitude_, Input_Coordinate_Format, "DMS", "JoinID", Spatial_Reference)
#3)Add XY coordinates to table. in_feat = out_data arcpy.AddXY_management(in_feat) print "XY points were successfully generated" #4) Convert Coordinates notation from Decimal degrees to decimal degree minutes #DD_2 to DDM_2 #make table view #arcpy.MakeTableView_management(in_feat, in_table) in_table = in_feat out_FC = "randomPts_" + date + "_DDM" x_field = "POINT_X" y_field = "POINT_Y" out_coord = "DDM_2" spat_ref = arcpy.SpatialReference( 3661) #'NAD_1983_NSRS2007_StatePlane_Tennessee_FIPS_4100') arcpy.ConvertCoordinateNotation_management(in_table, out_FC, x_field, y_field, "", out_coord, "", spat_ref) print "Successfully converted coordinate notation" #Delete GCS fc to clean up .gdb arcpy.Delete_management(in_table) arcpy.Delete_management(out_name)
def tableToPoint(inputTable, inputCoordinateFormat, inputXField, inputYField, outputPointFeatures, inputSpatialReference): ''' Converts table of coordinate formats to point features. inputTable - input table, each row will be a separate line feature in output inputCoordinateFormat - coordinate notation format of input vertices inputXField - field in inputTable for vertex x-coordinate, or full coordinate inputYField - field in inputTable for vertex y-coordinate, or None outputPointFeatures - output point features to create inputSpatialReference - spatial reference of input coordinates returns point feature class inputCoordinateFormat must be one of the following: * DD_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DD_2: Longitude and latitude values are in two separate fields. * DDM_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DDM_2: Longitude and latitude values are in two separate fields. * DMS_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DMS_2: Longitude and latitude values are in two separate fields. * GARS: Global Area Reference System. Based on latitude and longitude, it divides and subdivides the world into cells. * GEOREF: World Geographic Reference System. A grid-based system that divides the world into 15-degree quadrangles and then subdivides into smaller quadrangles. * UTM_ZONES: The letter N or S after the UTM zone number designates only North or South hemisphere. * UTM_BANDS: The letter after the UTM zone number designates one of the 20 latitude bands. N or S does not designate a hemisphere. * USNG: United States National Grid. Almost exactly the same as MGRS but uses North American Datum 1983 (NAD83) as its datum. * MGRS: Military Grid Reference System. Follows the UTM coordinates and divides the world into 6-degree longitude and 20 latitude bands, but MGRS then further subdivides the grid zones into smaller 100,000-meter grids. These 100,000-meter grids are then divided into 10,000-meter, 1,000-meter, 100-meter, 10-meter, and 1-meter grids. ''' try: env.overwriteOutput = True deleteme = [] scratch = '%scratchGDB%' if env.scratchWorkspace: scratch = env.scratchWorkspace inputSpatialReference = _checkSpatialRef(inputSpatialReference) if (inputCoordinateFormat == 'DD_2') and (inputSpatialReference is not None) and \ (inputSpatialReference != arcpy.SpatialReference(4326)): # default is GCS_WGS_1984 - if the SR is different, create feature class first using XYTableToPoint/MakeXYEventLayer # make scratch name for temp FC scratch_name = arcpy.CreateScratchName("temp", data_type="Featureclass", workspace=scratch) layername = os.path.basename(scratch_name) + "-layer" tempLayerOut = arcpy.management.MakeXYEventLayer( inputTable, inputXField, inputYField, layername, inputSpatialReference) scratch_out = arcpy.management.CopyFeatures( tempLayerOut, scratch_name) # Use the geometry of the scratch feature class, with SHAPE keyword, ingnores X and Y values arcpy.ConvertCoordinateNotation_management( scratch_out, outputPointFeatures, inputXField, inputYField, "SHAPE", "#", "#", inputSpatialReference) # Delete scratch dataset arcpy.Delete_management(scratch_out) else: #Using Geographic coordinates arcpy.ConvertCoordinateNotation_management( inputTable, outputPointFeatures, inputXField, inputYField, inputCoordinateFormat, "DD_NUMERIC", "#", inputSpatialReference) return outputPointFeatures except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) print(msgs) except: # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str( sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n" # Return python error messages for use in script tool or Python Window arcpy.AddError(pymsg) arcpy.AddError(msgs) # Print Python error messages for use in Python / Python Window print(pymsg + "\n") print(msgs) finally: if len(deleteme) > 0: # cleanup intermediate datasets if debug == True: arcpy.AddMessage("Removing intermediate datasets...") for i in deleteme: if debug == True: arcpy.AddMessage("Removing: " + str(i)) arcpy.Delete_management(i) if debug == True: arcpy.AddMessage("Done")
def tableToPolyline(inputTable, inputCoordinateFormat, inputXField, inputYField, outputPolylineFeatures, inputLineField, inputSortField, inputSpatialReference): ''' Converts a table of vertices to one or more polyline features. inputTable - input table, each row is a vertex inputCoordinateFormat - coordinate notation format of input vertices inputXField - field in inputTable for vertex x-coordinate, or full coordinate inputYField - field in inputTable for vertex y-coordinate, or None outputPolylineFeatures - polyline feature class to create inputLineField - field in inputTable to identify separate polylines inputSortField - field in inputTable to sort vertices inputSpatialReference - spatial reference of input coordinates returns polyline feature class inputCoordinateFormat must be one of the following: * DD_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DD_2: Longitude and latitude values are in two separate fields. * DDM_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DDM_2: Longitude and latitude values are in two separate fields. * DMS_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DMS_2: Longitude and latitude values are in two separate fields. * GARS: Global Area Reference System. Based on latitude and longitude, it divides and subdivides the world into cells. * GEOREF: World Geographic Reference System. A grid-based system that divides the world into 15-degree quadrangles and then subdivides into smaller quadrangles. * UTM_ZONES: The letter N or S after the UTM zone number designates only North or South hemisphere. * UTM_BANDS: The letter after the UTM zone number designates one of the 20 latitude bands. N or S does not designate a hemisphere. * USNG: United States National Grid. Almost exactly the same as MGRS but uses North American Datum 1983 (NAD83) as its datum. * MGRS: Military Grid Reference System. Follows the UTM coordinates and divides the world into 6-degree longitude and 20 latitude bands, but MGRS then further subdivides the grid zones into smaller 100,000-meter grids. These 100,000-meter grids are then divided into 10,000-meter, 1,000-meter, 100-meter, 10-meter, and 1-meter grids. ''' try: env.overwriteOutput = True deleteme = [] joinFieldName = "JoinID" scratch = '%scratchGDB%' if env.scratchWorkspace: scratch = env.scratchWorkspace inputSpatialReference = _checkSpatialRef(inputSpatialReference) copyRows = os.path.join(scratch, "copyRows") arcpy.CopyRows_management(inputTable, copyRows) addUniqueRowID(copyRows, joinFieldName) copyCCN = os.path.join(scratch, "copyCCN") arcpy.ConvertCoordinateNotation_management(copyRows, copyCCN, inputXField, inputYField, inputCoordinateFormat, "DD_NUMERIC", joinFieldName, inputSpatialReference) arcpy.PointsToLine_management(copyCCN, outputPolylineFeatures, inputLineField, inputSortField, "NO_CLOSE") return outputPolylineFeatures except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) print(msgs) except: # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str( sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n" # Return python error messages for use in script tool or Python Window arcpy.AddError(pymsg) arcpy.AddError(msgs) # Print Python error messages for use in Python / Python Window print(pymsg + "\n") print(msgs) finally: if len(deleteme) > 0: # cleanup intermediate datasets if debug == True: arcpy.AddMessage("Removing intermediate datasets...") for i in deleteme: if debug == True: arcpy.AddMessage("Removing: " + str(i)) arcpy.Delete_management(i) if debug == True: arcpy.AddMessage("Done")
envTable = arcpy.GetParameterAsText(3) # Excel master list table # 1. Import the Envi monitoring master list table out_name = "monitor_table" tableGDB = arcpy.TableToTable_conversion(envTable, workSpace, out_name) # 2. Convert coordinate notation from DMS2 to DD2 (generate a point feature layer) # set parameter values output_points = 'env_monitor_point' x_field = 'Longitude' y_field = 'Latitude' input_format = 'DMS_2' output_format = 'DD_2' spatial_ref = arcpy.SpatialReference('WGS 1984') xyP = arcpy.ConvertCoordinateNotation_management(tableGDB, output_points, x_field, y_field, input_format, output_format, "", spatial_ref) # create a spatial reference object for the output coordinate system out_coordinate_system = arcpy.SpatialReference(3857) # WGS84 Auxiliary # run the tool output_feature_class = "env_monitor_point_prj3857" xyP_prj = arcpy.Project_management(xyP, output_feature_class, out_coordinate_system) # 3. Truncate the main feature layer arcpy.TruncateTable_management(source_fgdb) # 4. Append the point FL to the main FL arcpy.Append_management(xyP_prj, source_fgdb, schema_type = 'NO_TEST')
if not os.path.exists(str(path) + "Base\\") or not os.path.exists( str(path) + "Base\\Base.shp"): raise IOError("Mask is Required!") else: pass print("How many points: " + str(PX * PY)) points = [] stepX = (endX - startX) / PX stepY = (endY - startY) / PY for i in range(PX): for j in range(PY): pointX = startX + (i + 1) * stepX pointY = startY + (j + 1) * stepY points.append([str(pointX), str(pointY)]) with open(path + "Middle\\Points.csv", 'a+b') as f: writer = csv.writer(f) writer.writerow(["X", "Y"]) for point in points: writer.writerow(point) arcpy.ConvertCoordinateNotation_management( str(path) + "Middle\\Points.csv", str(path) + "Points\\Points.shp", 'X', 'Y', 'DD_2', 'DD_2', '', spatial_ref, in_coor_system) arcpy.ErasePoint_edit( str(path) + "Points\\Points.shp", str(path) + "Base\\Base.shp", "OUTSIDE")
?s netowl:Entity.Numeric.Coordinate.Mgrs..name ?o . ?s rdfs:label ?label . } """) mgrs.set_index("o") mgrs_file = os.path.join(rdfOutDir,'mgrs_coords.csv') mgrs.to_csv(mgrs_file, sep=',', encoding='utf-8') #Converts coordinates located in the MGRS CSV into Lat/Longs, turns this into a shapefile outShpDir = os.path.join(rdfOutDir, 'OutShp') outName = outBaseName + 'MGRS.shp' if os.path.exists(outShpDir) == False: os.mkdir(outShpDir, mode=0o777,) arcpy.ConvertCoordinateNotation_management(in_table=mgrs_file, out_featureclass=os.path.join(outShpDir,outName), x_field="o", y_field="o", input_coordinate_format="MGRS", output_coordinate_format="DD_NUMERIC", id_field="", spatial_reference="GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119522E-09;0.001;0.001;IsHighPrecision", in_coor_system="GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]", exclude_invalid_records="INCLUDE_INVALID") #Zips up the shapefile created in the previous step outZip = fileOutDir def zipShapefilesInDir(inDir, outDir): if not os.path.exists(inDir): arcpy.AddMessage("Input directory %s does not exist!" % inDir) return False if not os.path.exists(outDir): arcpy.AddMessage("Creating output directory %s" % outDir) os.mkdir(outDir) arcpy.AddMessage("Zipping shapefile(s) in folder %s to output folder %s" % (inDir, outDir))
def main(): ''' main script function to put it all together ''' try: # get/set environment env.overwriteOutput = True env.scratchWorkspace = import_archive_folder # get list of GZ files in the import folder gzFiles = glob.glob(os.path.join(import_archive_folder,"*.gz")) if debug == True: arcpy.AddMessage("Found these files: " + str(gzFiles)) # GZ To Table for gzFile in gzFiles: datFiles.append(extract_archive(gzFile)) # Table To Points for datFile in datFiles: pntFile = pointName(datFile) arcpy.AddMessage("Converting " + os.path.basename(datFile) + " to points (" + os.path.basename(pntFile) + "). This will take several minutes.") # arcpy.MakeXYEventLayer_management(datFile, "lon", "lat", os.path.basename(datFile),GCS_WGS_1984, "") # arcpy.FeatureClassToFeatureClass_conversion(os.path.basename(datFile), os.path.dirname(pntFile), os.path.basename(pntFile)) arcpy.ConvertCoordinateNotation_management(datFile,pntFile,"lon","lat","DD_2","DD_NUMERIC","",GCS_WGS_1984, GCS_WGS_1984) featureClasses.append(pntFile) # Points To Rasters if pntFile.find("elv") != -1: outRasterDataset = os.path.join(output_raster_workspace,"elv_ras") # process as elevation arcpy.AddMessage("Building " + "elv_ras") arcpy.PointToRaster_conversion(pntFile,"elev",outRasterDataset) outputRasterDatasets.append(outRasterDataset) else: for monthField in fieldList: outRasterName = os.path.basename(pntFile).split("_")[0] + "_" + str(monthField) if (arcpy.Describe(output_raster_workspace).workspaceType == "FileSystem"): outRasterName = outRasterName + ".tif" # if our output workspace is a folder, make the rasters as TIFFs outRasterDataset= os.path.join(output_raster_workspace,outRasterName) arcpy.AddMessage("Building " + outRasterName) if debug == True: arcpy.AddMessage("RasterDataset: " + str(outRasterDataset)) arcpy.PointToRaster_conversion(pntFile,monthField,outRasterDataset) outputRasterDatasets.append(outRasterDataset) if debug == True: arcpy.AddMessage("DONE -----------------") # Set output arcpy.SetParameter(2,outputRasterDatasets) except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) print(msgs) except: # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n" # Return python error messages for use in script tool or Python Window arcpy.AddError(pymsg) arcpy.AddError(msgs) # Print Python error messages for use in Python / Python Window print(pymsg + "\n") print(msgs)
def tableTo2PointLine(inputTable, inputStartCoordinateFormat, inputStartXField, inputStartYField, inputEndCoordinateFormat, inputEndXField, inputEndYField, outputLineFeatures, inputLineType, inputSpatialReference): ''' Creates line features from a start point coordinate and an endpoint coordinate. inputTable - Input Table inputStartCoordinateFormat - Start Point Format (from Value List) inputStartXField - Start X Field (longitude, UTM, MGRS, USNG, GARS, GEOREF)(from Input Table) inputStartYField - Start Y Field (latitude)(from Input Table) inputEndCoordinateFormat - End Point Format (from Value List) inputEndXField - End X Field (longitude, UTM, MGRS, USNG, GARS, GEOREF)(from Input Table) inputEndYField - End Y Field (latitude) (from Input Table) outputLineFeatures - Output Line inputLineType - Line Type (from Value List) inputSpatialReference - Spatial Reference, default is GCS_WGS_1984 returns line feature class inputStartCoordinateFormat and inputEndCoordinateFormat must be one of the following: * DD_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DD_2: Longitude and latitude values are in two separate fields. * DDM_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DDM_2: Longitude and latitude values are in two separate fields. * DMS_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DMS_2: Longitude and latitude values are in two separate fields. * GARS: Global Area Reference System. Based on latitude and longitude, it divides and subdivides the world into cells. * GEOREF: World Geographic Reference System. A grid-based system that divides the world into 15-degree quadrangles and then subdivides into smaller quadrangles. * UTM_ZONES: The letter N or S after the UTM zone number designates only North or South hemisphere. * UTM_BANDS: The letter after the UTM zone number designates one of the 20 latitude bands. N or S does not designate a hemisphere. * USNG: United States National Grid. Almost exactly the same as MGRS but uses North American Datum 1983 (NAD83) as its datum. * MGRS: Military Grid Reference System. Follows the UTM coordinates and divides the world into 6-degree longitude and 20 latitude bands, but MGRS then further subdivides the grid zones into smaller 100,000-meter grids. These 100,000-meter grids are then divided into 10,000-meter, 1,000-meter, 100-meter, 10-meter, and 1-meter grids. inputLineType must be one of the following: * GEODESIC: * GREAT_CIRCLE: * RHUMB_LINE: * NORMAL_SECTION: ''' try: # get/set environment env.overwriteOutput = True deleteme = [] scratch = '%scratchGDB%' joinFieldName = "JoinID" startXFieldName = "startX" startYFieldName = "startY" endXFieldName = "endX" endYFieldName = "endY" if env.scratchWorkspace: scratch = env.scratchWorkspace inputSpatialReference = _checkSpatialRef(inputSpatialReference) copyRows = os.path.join(scratch, "copyRows") arcpy.CopyRows_management(inputTable, copyRows) originalTableFieldNames = _tableFieldNames(inputTable, joinExcludeFields) addUniqueRowID(copyRows, joinFieldName) #Convert Start Point arcpy.AddMessage("Formatting start point...") startCCN = os.path.join(scratch, "startCCN") arcpy.ConvertCoordinateNotation_management(copyRows, startCCN, inputStartXField, inputStartYField, inputStartCoordinateFormat, "DD_NUMERIC", joinFieldName) arcpy.AddField_management(startCCN, startXFieldName, "DOUBLE") arcpy.CalculateField_management(startCCN, startXFieldName, "!DDLon!", "PYTHON_9.3") arcpy.AddField_management(startCCN, startYFieldName, "DOUBLE") arcpy.CalculateField_management(startCCN, startYFieldName, "!DDLat!", "PYTHON_9.3") arcpy.JoinField_management(copyRows, joinFieldName, startCCN, joinFieldName, [startXFieldName, startYFieldName]) #Convert End Point arcpy.AddMessage("Formatting end point...") endCCN = os.path.join(scratch, "endCCN") arcpy.ConvertCoordinateNotation_management(copyRows, endCCN, inputEndXField, inputEndYField, inputEndCoordinateFormat, "DD_NUMERIC", joinFieldName) arcpy.AddField_management(endCCN, endXFieldName, "DOUBLE") arcpy.CalculateField_management(endCCN, endXFieldName, "!DDLon!", "PYTHON_9.3") arcpy.AddField_management(endCCN, endYFieldName, "DOUBLE") arcpy.CalculateField_management(endCCN, endYFieldName, "!DDLat!", "PYTHON_9.3") arcpy.JoinField_management(copyRows, joinFieldName, endCCN, joinFieldName, [endXFieldName, endYFieldName]) #XY TO LINE arcpy.AddMessage( "Connecting start point to end point as {0}...".format( inputLineType)) arcpy.XYToLine_management(copyRows, outputLineFeatures, startXFieldName, startYFieldName, endXFieldName, endYFieldName, inputLineType, joinFieldName, inputSpatialReference) #Join original table fields to output arcpy.AddMessage( "Joining fields from input table to output line features...") arcpy.JoinField_management(outputLineFeatures, joinFieldName, copyRows, joinFieldName, originalTableFieldNames) arcpy.DeleteField_management(outputLineFeatures, [ joinFieldName, startXFieldName, startYFieldName, endXFieldName, endYFieldName ]) return outputLineFeatures except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) print(msgs) except: # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str( sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n" # Return python error messages for use in script tool or Python Window arcpy.AddError(pymsg) arcpy.AddError(msgs) # Print Python error messages for use in Python / Python Window print(pymsg + "\n") print(msgs) finally: if len(deleteme) > 0: # cleanup intermediate datasets if debug == True: arcpy.AddMessage("Removing intermediate datasets...") for i in deleteme: if debug == True: arcpy.AddMessage("Removing: " + str(i)) arcpy.Delete_management(i) if debug == True: arcpy.AddMessage("Done")
del writeRows # Get Weapon Position as points arcpy.AddMessage("Finding weapon position MGRS ...") arcpy.MakeXYEventLayer_management(outputExtentBoxes, "WeaponX", "WeaponY", "XYEvent", inputFeatureSR) arcpy.CopyFeatures_management("XYEvent", outputWeaponPositions) tempGeoPoints = os.path.join(scratch, "tempGeoPoints") deleteme.append(tempGeoPoints) arcpy.Project_management(outputWeaponPositions, tempGeoPoints, GCS_WGS_1984) arcpy.AddXY_management(tempGeoPoints) tempCCNPoints = os.path.join("in_memory", "tempCCNPoints") deleteme.append(tempCCNPoints) arcpy.ConvertCoordinateNotation_management(tempGeoPoints, tempCCNPoints, "POINT_X", "POINT_Y", "DD_2", "MGRS", "RFID", GCS_WGS_1984) arcpy.JoinField_management(outputWeaponPositions, "RFID", tempCCNPoints, "RFID", ["MGRS"]) # ENHANCEMENT: add Range Rings for each weapon position # set script output parameter arcpy.SetParameter(1, outputExtentBoxes) arcpy.SetParameter(2, outputWeaponPositions) except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) print msgs
def tableToLineOfBearing(inputTable, inputCoordinateFormat, inputXField, inputYField, inputBearingUnits, inputBearingField, inputDistanceUnits, inputDistanceField, outputLineFeatures, inputLineType, inputSpatialReference): ''' Tool method for converting a table of starting points, bearings, and distances to line features. inputTable - input table, each row will be a separate line feature in output inputCoordinateFormat - coordinate notation format of input vertices inputXField - field in inputTable for vertex x-coordinate, or full coordinate inputYField - field in inputTable for vertex y-coordinate, or None inputBearingUnits - inputBearingField - inputDistanceUnits - inputDistanceField - outputLineFeatures - polyline feature class to create inputLineType - inputSpatialReference - spatial reference of input coordinates returns polyline feature class inputCoordinateFormat must be one of the following: * DD_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DD_2: Longitude and latitude values are in two separate fields. * DDM_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DDM_2: Longitude and latitude values are in two separate fields. * DMS_1: Both longitude and latitude values are in a single field. Two values are separated by a space, a comma, or a slash. * DMS_2: Longitude and latitude values are in two separate fields. * GARS: Global Area Reference System. Based on latitude and longitude, it divides and subdivides the world into cells. * GEOREF: World Geographic Reference System. A grid-based system that divides the world into 15-degree quadrangles and then subdivides into smaller quadrangles. * UTM_ZONES: The letter N or S after the UTM zone number designates only North or South hemisphere. * UTM_BANDS: The letter after the UTM zone number designates one of the 20 latitude bands. N or S does not designate a hemisphere. * USNG: United States National Grid. Almost exactly the same as MGRS but uses North American Datum 1983 (NAD83) as its datum. * MGRS: Military Grid Reference System. Follows the UTM coordinates and divides the world into 6-degree longitude and 20 latitude bands, but MGRS then further subdivides the grid zones into smaller 100,000-meter grids. These 100,000-meter grids are then divided into 10,000-meter, 1,000-meter, 100-meter, 10-meter, and 1-meter grids. inputBearingUnits must be one of the following: * DEGREES * MILS * RADS * GRAD inputDistanceUnits must be one of the following: * METERS * KILOMETERS * MILES * NAUTICAL_MILES * FEET * US_SURVEY_FEET inputLineType must be one of the following: * GEODESIC: * GREAT_CIRCLE: * RHUMB_LINE: * NORMAL_SECTION: ''' try: env.overwriteOutput = True deleteme = [] joinFieldName = "JoinID" scratch = '%scratchGDB%' if env.scratchWorkspace: scratch = env.scratchWorkspace inputSpatialReference = _checkSpatialRef(inputSpatialReference) copyRows = os.path.join(scratch, "copyRows") arcpy.CopyRows_management(inputTable, copyRows) originalTableFieldNames = _tableFieldNames(inputTable, joinExcludeFields) addUniqueRowID(copyRows, joinFieldName) arcpy.AddMessage("Formatting start point...") copyCCN = os.path.join(scratch, "copyCCN") arcpy.ConvertCoordinateNotation_management(copyRows, copyCCN, inputXField, inputYField, inputCoordinateFormat, "DD_NUMERIC", joinFieldName, inputSpatialReference) arcpy.AddMessage("Creating lines as {0}...".format(inputLineType)) arcpy.BearingDistanceToLine_management( copyCCN, outputLineFeatures, "DDLon", "DDLat", inputDistanceField, inputDistanceUnits, inputBearingField, inputBearingUnits, inputLineType, joinFieldName, inputSpatialReference) #Join original table fields to output arcpy.AddMessage( "Joining fields from input table to output line features...") arcpy.JoinField_management(outputLineFeatures, joinFieldName, copyRows, joinFieldName, originalTableFieldNames) arcpy.DeleteField_management(outputLineFeatures, [joinFieldName]) return outputLineFeatures except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) print(msgs) except: # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str( sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n" # Return python error messages for use in script tool or Python Window arcpy.AddError(pymsg) arcpy.AddError(msgs) # Print Python error messages for use in Python / Python Window print(pymsg + "\n") print(msgs) finally: if len(deleteme) > 0: # cleanup intermediate datasets if debug == True: arcpy.AddMessage("Removing intermediate datasets...") for i in deleteme: if debug == True: arcpy.AddMessage("Removing: " + str(i)) arcpy.Delete_management(i) if debug == True: arcpy.AddMessage("Done")
arcpy.CopyFeatures_management(inFeature, copyInFeatures) delete_me.append(copyInFeatures) layerSymLocation = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', 'layers')) mxd = arcpy.mapping.MapDocument('CURRENT') df = arcpy.mapping.ListDataFrames(mxd)[0] prjImpactPoints = os.path.join(outWorkspace, scrubbedImpactOutPrefix) arcpy.AddMessage("Projecting input points to Web Mercator ...") arcpy.Project_management(copyInFeatures, prjImpactPoints, webMercator) layerToAdd = arcpy.mapping.Layer(copyInFeatures) arcpy.AddXY_management(layerToAdd) arcpy.ConvertCoordinateNotation_management(layerToAdd, prjImpactPoints, "Point_X", "Point_Y", "SHAPE", "MGRS") layerToAdd = arcpy.mapping.Layer(prjImpactPoints) arcpy.ApplySymbologyFromLayer_management( layerToAdd, layerSymLocation + "\Impact Point Centers.lyr") arcpy.mapping.AddLayer(df, layerToAdd, "AUTO_ARRANGE") #delete_me.append(prjImpactPoints) #Loop through the weapons and create create the Point of Origin for each for index in range(len(models)): model = models[index] scrubbedModel = ''.join(e for e in model if (e.isalnum() or e == " " or e == "_")) scrubbedModel = scrubbedModel.replace(" ", "_") if DEBUG == True:
scratch = 'in_memory' env.scratchWorkspace = 'in_memory' if DEBUG == True: arcpy.AddMessage("scratch: " + str(scratch)) if outputCoordinateSystemAsText == '': outputCoordinateSystem = arcpy.Describe(inFeature).spatialReference arcpy.AddWarning("Spatial Reference is not defined. Using Spatial Reference of Impact Points: " + str(outputCoordinateSystem .name)) env.outputCoordinateSystem = outputCoordinateSystem arcpy.AddMessage("Building impact points...") copyInFeatures = os.path.join(scratch,"copyInFeatures") outputImpactPointFeatures = os.path.join(outWorkspace,scrubbedImpactOutPrefix) arcpy.CopyFeatures_management(inFeature,copyInFeatures) delete_me.append(copyInFeatures) arcpy.AddXY_management(copyInFeatures) arcpy.ConvertCoordinateNotation_management(copyInFeatures,outputImpactPointFeatures, "Point_X", "Point_Y", "SHAPE", "MGRS") delete_me.append(copyInFeatures) modelOriginsDict = {} #modelOriginsDict[scrubbedModel] = [{"ranges":impactPointBuffersList},{"combined":output_poo}] #Loop through the weapons and create create the Point of Origin for each for indexWeaponModel in range(len(selectedWeaponModels)): selectedModel = selectedWeaponModels[indexWeaponModel] scrubbedModel = ''.join(e for e in selectedModel if (e.isalnum() or e == " " or e == "_")) scrubbedModel = scrubbedModel.replace(" ", "_") arcpy.AddMessage("Getting Range for: " + selectedModel) if DEBUG == True: arcpy.AddMessage("Model: " + selectedModel) arcpy.AddMessage("Scrubbed Model: " + scrubbedModel)
def IPPplot(iPPtype, cUnits, xyIPP, iNcdName, SubName, spatRef): if iPPtype == 'ICP': ipPoint = 'AssetPts' iType = 'AssetType' iPPtype = 1 iLat = 'LATITUDE' iLong = 'LONGITUDE' else: ipPoint='Planning_Points' iType = 'IPPType' iLat = 'Latitude' iLong = 'Longitude' CoordUnits = cUnits.upper() geoUnits=['DECIMAL DEGREES','DEGREES MINUTES SECONDS','DEGREES DECIMAL MINUTES'] projUnits = ['MGRS', 'US NATIONAL GRID', 'UTM'] spatialRef_Out=spatRef #target output spatial reference arcpy.AddMessage(spatialRef_Out.name) SR_geo = arcpy.SpatialReference('WGS 1984') if CoordUnits in geoUnits: xy = geoCoords(xyIPP) spatialRef_In = SR_geo if CoordUnits == 'DECIMAL DEGREES': inFormat = 'DD_1' elif CoordUnits == 'DEGREES MINUTES SECONDS': inFormat = 'DMS_1' elif CoordUnits == 'DEGREES DECIMAL MINUTES': inFormat = 'DDM_1' elif CoordUnits in projUnits: xy=xyIPP spatialRef_In = spatRef if CoordUnits == 'MGRS': inFormat = 'MGRS' elif CoordUnits == 'US NATIONAL GRID': inFormat = 'USNG' elif CoordUnits == 'UTM': inFormat = 'UTM_ZONES' else: arcpy.AddErrorMessage('Improper Coordinate System') sys.exit('Improper Coordinate System') xyTemp='xyTemplate' TempTbl = path.join(wrkspc, xyTemp) if not arcpy.Exists(TempTbl): arcpy.AddMessage("Missing Table: {}".format(xyTemp)) arcpy.CreateTable_management(wrkspc, xyTemp) #Add fields fldName = ["x_Field","y_Field","in_Coord","out_Coord"] for fld in fldName: arcpy.AddField_management(xyTemp,fld,"TEXT",field_length=100) # try: outFlds=['x_Field', 'in_Coord','out_Coord'] outInfo=[xy, spatialRef_In.name, spatialRef_Out.name] cursor = arcpy.da.InsertCursor(TempTbl, outFlds) cursor.insertRow(outInfo) del cursor # except: # arcpy.AddMessage("Could not add IPP/ICP. Please add manually") # sys.exit(0) # set parameter values outFC = path.join(wrkspc, 'TempPoint') x_field = 'x_Field' outFormat = 'DD_NUMERIC' arcpy.ConvertCoordinateNotation_management(TempTbl, outFC, x_field, "", inFormat, \ outFormat, "", spatialRef_Out, spatialRef_In) try: arcpy.DeleteRows_management(TempTbl) except: pass expression="""{} = '{}'""".format(arcpy.AddFieldDelimiters(outFC, x_field),xy) cursor = arcpy.da.SearchCursor(outFC, [x_field, "DDLat", "DDLon"], where_clause=expression) pt = arcpy.Point() try: for row in cursor: pt.X=row[2] pt.Y=row[1] arcpy.AddMessage("Lat: {}, Long: {}".format(pt.Y, pt.X)) except: pass del cursor if arcpy.Exists(outFC): arcpy.Delete_management(outFC) ptGeo=arcpy.PointGeometry(pt, SR_geo) fc = path.join(wrkspc,ipPoint) if ipPoint =="Planning_Points": cursor = arcpy.da.InsertCursor(fc,[iType,"SubjectID", iLat, iLong, "SHAPE@"]) cursor.insertRow([iPPtype,1, pt.Y, pt.X, ptGeo]) else: cursor = arcpy.da.InsertCursor(fc,[iType,"Status", iLat, iLong, "SHAPE@"]) arcpy.Delete_management(outFC) cursor.insertRow([iPPtype,"Assigned", pt.Y, pt.X, ptGeo]) try: del cursor except: pass return