def createProject(dem, streamNetwork, clippingRegion, outputFolder, clippedStreamNetwork, outputName, spatialReference, intersectionArray): """ Copies everything over into a folder and writes the XML file for it :param dem: The path to the DEM :param streamNetwork: The path to the original stream network :param clippingRegion: The path to the clipping region, if applicable :param outputFolder: Where we want to put the project :param clippedStreamNetwork: The result of the clipping :param outputName: What we want to name our output :param spatialReference: The spatial reference of the stream network :param intersectionArray: The array of intersections that we have :return: None """ projectFolder = makeFolder(outputFolder, "TribImpactProject") inputsFolder = makeFolder(projectFolder, "01_Inputs") analysesFolder = makeFolder(projectFolder, "02_Analyses") demFolder = makeFolder(inputsFolder, "01_DEM") demTempLayer = os.path.join(demFolder, os.path.basename(dem) + "_lyr") demLayer = os.path.join(demFolder, os.path.basename(dem)[:-4] + ".lyr") demFile = os.path.join(demFolder, os.path.join(os.path.basename(dem))) arcpy.Copy_management(dem, demFile) symbologyFolder = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'symbology') # gives us the symbology folder demSymbology = os.path.join(symbologyFolder, "DEM.lyr") arcpy.MakeRasterLayer_management(demFile, demTempLayer) arcpy.SaveToLayerFile_management(demTempLayer, demLayer) arcpy.ApplySymbologyFromLayer_management(demLayer, demSymbology) arcpy.SaveToLayerFile_management(demLayer, demLayer) streamNetworkFolder = makeFolder(inputsFolder, "02_StreamNetwork") arcpy.Copy_management( streamNetwork, os.path.join(streamNetworkFolder, os.path.basename(streamNetwork))) streamNetworkOrig = os.path.join(streamNetworkFolder, os.path.basename(streamNetwork)) if clippingRegion: clippingRegionFolder = makeFolder(inputsFolder, "03_ClippingRegionFolder") arcpy.Copy_management( clippingRegion, os.path.join(clippingRegionFolder, os.path.basename(clippingRegion))) outputFolder = getOutputFolder(analysesFolder) writeOutput(intersectionArray, outputFolder, outputName, spatialReference, clippedStreamNetwork, demLayer, streamNetworkOrig)
def makeLayerPackage(outputDataPath, pointLayer, upstreamLayer, downstreamLayer, streamNetwork, demLayer, streamNetworkOrig): """ Applies symbology to layer files :param outputDataPath: What output folder we're in :param pointLayer: The layer points output :param upstreamLayer: The layer of upstream impact probabilities :param downstreamLayer: The layer of downstream impact probabilities :param streamNetwork: The stream network in the project folder :param demLayer: The DEM layer we made earlier :param streamNetworkOrig: The stream network file in the inputs folder :return: None """ #TODO Make a layer package? projectPath = os.path.dirname(os.path.dirname(outputDataPath)) tribCodeFolder = os.path.dirname(os.path.abspath(__file__)) symbologyFolder = os.path.join(tribCodeFolder, 'symbology') pointSymbology = os.path.join(symbologyFolder, "TribImpactPoints.lyr") upstreamSymbology = os.path.join(symbologyFolder, "TribImpactUpstream.lyr") downstreamSymbology = os.path.join(symbologyFolder, "TribImpactDownstream.lyr") arcpy.ApplySymbologyFromLayer_management(pointLayer, pointSymbology) arcpy.SaveToLayerFile_management(pointLayer, pointLayer) arcpy.ApplySymbologyFromLayer_management(upstreamLayer, upstreamSymbology) arcpy.SaveToLayerFile_management(upstreamLayer, upstreamLayer) arcpy.ApplySymbologyFromLayer_management(downstreamLayer, downstreamSymbology) arcpy.SaveToLayerFile_management(downstreamLayer, downstreamLayer) streamNetworkLayer = streamNetworkOrig[:-4] + '.lyr' arcpy.MakeFeatureLayer_management(streamNetworkOrig, streamNetworkLayer) arcpy.SaveToLayerFile_management(streamNetworkLayer, streamNetworkLayer) layerPackageFolder = makeFolder(outputDataPath, "03_LayerPackage") layerPackage = os.path.join(layerPackageFolder, "layerPackage.lpkx") layers = [ pointLayer, upstreamLayer, downstreamLayer, demLayer, streamNetworkLayer ] try: arcpy.PackageLayer_management(layers, layerPackage) except: arcpy.AddWarning( 'We could not package the output into a single layer package. This is often a result of a ' + 'known bug in ArcGIS 10.6. You may try packaging the outputs together yourself if you wish' )
def makeLayer(output_folder, layer_base, new_layer_name, symbology_layer, isRaster, description="Made Up Description"): """ Creates a layer and applies a symbology to it :param output_folder: Where we want to put the folder :param layer_base: What we should base the layer off of :param new_layer_name: What the layer should be called :param symbology_layer: The symbology that we will import :param isRaster: Tells us if it's a raster or not :param description: The discription to give to the layer file :return: The path to the new layer """ new_layer = new_layer_name + "_lyr" new_layer_save = os.path.join(output_folder, new_layer_name + ".lyr") if isRaster: arcpy.MakeRasterLayer_management(layer_base, new_layer) else: arcpy.MakeFeatureLayer_management(layer_base, new_layer) arcpy.ApplySymbologyFromLayer_management(new_layer, symbology_layer) arcpy.SaveToLayerFile_management(new_layer, new_layer_save) new_layer_instance = arcpy.mapping.Layer(new_layer_save) new_layer_instance.description = description new_layer_instance.save() return new_layer_save
def makeLyrFromMXD(inMXD, outLyr): if not (os.path.exists(inMXD)): printit("ERROR: {} does not exist".format(inMXD)) return False if not (os.path.exists(EmptyGroupLayerFile)): printit("ERROR: {} does not exist".format(EmptyGroupLayerFile)) return False if (os.path.exists(outLyr)): printit("Skipping: {} already exists".format(outLyr)) return True printit("Making Layer file: {0}".format(outLyr)) mxd = arcpy.mapping.MapDocument(inMXD) ###Right now, just doing the first Dataframe, this could be modified df = arcpy.mapping.ListDataFrames(mxd)[0] theUUID = str(uuid.uuid1()) iGroupLayerRaw = arcpy.mapping.Layer(EmptyGroupLayerFile) iGroupLayerRaw.name = theUUID arcpy.mapping.AddLayer(df, iGroupLayerRaw, "TOP") groupBaseName = os.path.basename(outLyr).split(".")[0] for lyr in arcpy.mapping.ListLayers(df): if not (lyr.name == theUUID): if (lyr.longName == lyr.name): arcpy.mapping.AddLayerToGroup(df, iGroupLayer, lyr, "Bottom") else: iGroupLayer = lyr iGroupLayer.name = groupBaseName arcpy.SaveToLayerFile_management(iGroupLayer, outLyr) return os.path.exists(outLyr)
def writeAnalyses(projectFolder, reachArray, outputName, sr): """ Writes the analyses folder and the output of the tool run :param projectFolder: Where we want to put stuff :param reachArray: The array of reaches that we created with our tool :param outputName: The name of what we want to put out :param sr: The spatial reference of the stream network :return: None """ analysesFolder = makeFolder(projectFolder, "02_Analyses") outputFolder = getOutputFolder(analysesFolder) outputShape = arcpy.CreateFeatureclass_management(outputFolder, outputName + ".shp", "POLYLINE", "", "DISABLED", "DISABLED", sr) arcpy.AddField_management(outputShape, "Regime", "TEXT") insertCursor = arcpy.da.InsertCursor(outputShape, ["SHAPE@", "Regime"]) for reach in reachArray: insertCursor.insertRow([reach.polyline, reach.classification]) del insertCursor tempLayer = outputFolder + "\\" + outputName + "_lyr" outputLayer = outputFolder + "\\" + outputName + ".lyr" arcpy.MakeFeatureLayer_management(outputShape, tempLayer) arcpy.SaveToLayerFile_management(tempLayer, outputLayer)
def onClick(self): try: workspace = autoPath() mxd = arcpy.mapping.MapDocument("CURRENT") ddp = mxd.dataDrivenPages dfLst = arcpy.mapping.ListDataFrames(mxd) pageName = ddp.pageRow.getValue(ddp.pageNameField.name) # Set data frame name to credits field (can change to description field) for use in lyrString. for df in dfLst: for lyr in arcpy.mapping.ListLayers(mxd, "*", df): if isinstance( lyr, arcpy.mapping.Layer) and not lyr.isGroupLayer: lyr.credits = df.name lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame() if not isinstance(lyr, arcpy.mapping.Layer) or lyr.isGroupLayer: pythonaddins.MessageBox( 'Please select one (1) layer (not a group or data frame or multiple layers) in the Table Of Contents', 'Layer Selection Error', 0) else: lyrString = "%s_%s_%s.lyr" % (pageName, lyr.name, lyr.credits) arcpy.SaveToLayerFile_management(lyr, workspace + "\\" + lyrString, "ABSOLUTE") pythonaddins.MessageBox( "%s layer saved to:\n\n%s\n\nas:\n\n%s" % (lyr.name, workspace, lyrString), "Layer Saved", 0) except Exception as e: pythonaddins.MessageBox(e, "Error")
def make_layers(huc_shp, symbologyList, nameList, outputFolder): # Creates all necessary layers, given a list of symbology filepaths and names for the files # Initialize Variables layerPathList = [] # Create every layer for symbology, name in zip(symbologyList, nameList): print "\nCreating Layer: " + name + "...\n" # Make a new layer with a name from the nameList newLayer = arcpy.MakeFeatureLayer_management(huc_shp, name) # Apply appropriate symbology from the symbology List arcpy.ApplySymbologyFromLayer_management(newLayer, symbology) # Create a filepath to save the layer filePath = clean_filepath(os.path.join(outputFolder, (name + "_Summary.lyr"))) # Check to see if the layer we are looking at is the reference labels file, as that has special considerations if symbology == os.path.join(symbology_folder, "Summary_Labels.lyr"): temp = symbolize_labels(newLayer, filePath, symbology, outputFolder) newLayer = temp # Save the layer arcpy.SaveToLayerFile_management(newLayer, filePath) # Add this filepath to a list. This will be used to create the layer package layerPathList.append(filePath) return layerPathList
def ExtractVar( DtLst, RLst, Key, Spr, Fldr ): ##### Extraction of Snow Values from Rasters to UHDB Station Points and Cleaned for negative values or null values if not os.path.exists(Fldr): os.makedirs(Fldr) X_pts = "LONGITUDE" Y_pts = "LATITUDE" ValueField = "SNOWFALL" Workspc = Fldr arcpy.env.workspace = Workspc env.overwriteOutput = True for i in range(0, len(DtLst)): Yr = str(DtLst[i][0:4]) Mo = str(DtLst[i][5:7]) Dy = str(DtLst[i][8:10]) Date = str(DtLst[i]) UHDB_Name = "UHDBSNOW" + Yr UHDBgdb = os.path.join(Workspc, UHDB_Name + ".gdb") if not arcpy.Exists(UHDBgdb): arcpy.CreateFileGDB_management(Workspc, UHDB_Name) UHDBFc = "SNOW" + Yr + Mo + Dy UHDBShp = os.path.join(UHDBgdb, UHDBFc) NewLyr = "SNOW" + str(DtLst[i]) SvLyr = NewLyr + ".lyr" StationPts = arcpy.MakeXYEventLayer_management(Key, X_pts, Y_pts, NewLyr, Spr) UFDBPts = arcpy.SaveToLayerFile_management(StationPts, SvLyr) arcpy.CopyFeatures_management(UFDBPts, UHDBShp) print("Start Kriging") arcpy.sa.ExtractMultiValuesToPoints(UHDBShp, RLst[i], "NONE") DateField = "ObsDate" OldField = ValueField + Yr + "_" + Mo + "_" + Dy print(OldField) arcpy.AddField_management(UHDBShp, ValueField, "FLOAT", "6", "3", "", "", "", "", "") arcpy.AddField_management(UHDBShp, DateField, "TEXT", "", "", "10", "", "", "", "") NwFields = [OldField, ValueField, DateField] DFields = [ OldField, "NAME", "COUNTRY", "LATITUDE", "LONGITUDE", "ELEVATION", "STATE" ] print(NwFields) with arcpy.da.UpdateCursor(UHDBShp, NwFields) as ModCursor: for row in ModCursor: row[2] = Date if row[0] < int(0): row[1] = None row[2] = Date ModCursor.updateRow(row) else: row[1] = row[0] row[2] = Date ModCursor.updateRow(row) del ModCursor arcpy.DeleteField_management(UHDBShp, DFields) return UHDBgdb
def writeAnalyses(projectFolder, reachArray, sr): """ Writes the outputs :param projectFolder: Where we put our analyses :param reachArray: Our array of reaches with grain size data :param sr: The spatial reference of the output :return: """ analysesFolder = makeFolder(projectFolder, "02_Analyses") outputFolder = getOutputFolder(analysesFolder) outputShape = outputFolder + "\GrainSize.shp" tempLayer = outputFolder + "\GrainSize_lyr" outputLayer = outputFolder + "\GrainSize.lyr" arcpy.CreateFeatureclass_management(outputFolder, "GrainSize.shp", "POLYLINE", "", "DISABLED", "DISABLED", sr) arcpy.AddField_management(outputShape, "GrainSize", "DOUBLE") insertCursor = arcpy.da.InsertCursor(outputShape, ["SHAPE@", "GrainSize"]) for reach in reachArray: insertCursor.insertRow([reach.polyline, reach.grainSize]) del insertCursor arcpy.MakeFeatureLayer_management(outputShape, tempLayer) arcpy.SaveToLayerFile_management(tempLayer, outputLayer)
def executer(self, nomClasse, classeSNRC, requete, repTravail): #------------------------------------------------------------------------------------- """ Exécuter le traitement pour créer un Layer par Zone UTM contenant la classe de SNRC avec une requête correspondant à la sélection pour lesquels les éléments d'une classe sont présents dans le SNRC. Paramètres: ----------- nomClasse : Nom de la classe traité. classeSNRC : Nom de la FeatureClass contenant les éléments du découpage SNRC. requete : Requête attributive utilisé pour chaque Layer de zone UTM créée. repTravail : Nom du répertoire de travail dans lequel les Layers par zone UTM seront créés. Variables: ---------- """ #Forcer la destruction des fichiers de sortie arcpy.env.overwriteOutput = True #Traiter toutes les zone UTM for zoneUTM in range(7, 23): #Afficher la zone UTM traitée arcpy.AddMessage(" ") arcpy.AddMessage("-Traitement de la zone UTM :" + str(zoneUTM)) #Définir la requête par zone UTM requeteZoneUtm = requete.replace("[NOM_CLASSE]", nomClasse).replace( "[ZONE_UTM]", str(zoneUTM)) #Définir le nom du Layer des SNRC à traiter pour la zone UTM lyrDecoupage = "BDG_DBA.ges_Decoupage_SNRC50K_2" + "_" + str( zoneUTM) + ".lyr" #Process: Make Feature Layer arcpy.AddMessage('MakeFeatureLayer_management "' + classeSNRC + '" ' + requeteZoneUtm + '"') arcpy.MakeFeatureLayer_management(classeSNRC, lyrDecoupage, requeteZoneUtm) arcpy.AddMessage(arcpy.GetMessage(arcpy.GetMessageCount() - 1)) #Process: Select Layer By Attribute arcpy.AddMessage("SelectLayerByAttribute_management " + lyrDecoupage + " NEW_SELECTION") arcpy.SelectLayerByAttribute_management(lyrDecoupage, "NEW_SELECTION") arcpy.AddMessage(arcpy.GetMessage(arcpy.GetMessageCount() - 1)) #Process: Save To Layer File arcpy.AddMessage("SaveToLayerFile_management " + lyrDecoupage + " " + repTravail + "\\" + nomClasse + "\\" + lyrDecoupage) arcpy.SaveToLayerFile_management( lyrDecoupage, repTravail + "\\" + nomClasse + "\\" + lyrDecoupage) arcpy.AddMessage(arcpy.GetMessage(arcpy.GetMessageCount() - 1)) # Sortir du traitement return
def update_lyr_meta(output_lyr_path, output_dir_path): if not arcpy.Exists(output_lyr_path): print( "Feature layer does not currently exist for POPS on M:\GIS\DATA directories. Generating now" ) arcpy.env.workspace = r'in_memory' arcpy.MakeFeatureLayer_management(sde_pops_path, 'Privately Owned Public Spaces') arcpy.SaveToLayerFile_management('Privately Owned Public Spaces', output_lyr_path) print( "Exporting feature layer metadata to M:\GIS\DATA directories") arcpy.env.workspace = output_dir_path shutil.copy( os.path.join(current_meta_dir, 'nyc_pops_{}meta.xml'.format(production_date)), os.path.join(output_dir_path, 'Privately Owned Public Spaces.lyr.xml')) else: print( "Exporting feature layer metadata to M:\GIS\DATA directories") arcpy.env.workspace = output_dir_path arcpy.env.overwriteOutput = True shutil.copy( os.path.join(current_meta_dir, 'nyc_pops_{}meta.xml'.format(production_date)), os.path.join(output_dir_path, 'Privately Owned Public Spaces.lyr.xml'))
def show_things(thing_path, lyr_name, folder): gp = arcgisscripting.create() # Adding the layer to the table of contents mxd = arcpy.mapping.MapDocument("current") df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] file_type = arcpy.Describe(thing_path).dataType if file_type == u'RasterDataset': if not arcpy.Exists(thing_path): name_temp = os.path.join(folder, 'temp', '{}.tif'.format(os.path.split(thing_path)[-1])) arcpy.CopyRaster_management(thing_path, name_temp) arcpy.MakeRasterLayer_management(in_raster=name_temp, out_rasterlayer=lyr_name) else: arcpy.MakeRasterLayer_management(in_raster=thing_path, out_rasterlayer=lyr_name) elif (file_type == u'ShapeFile') or (file_type == u'FeatureClass'): if not arcpy.Exists(thing_path): name_temp = os.path.join(folder, 'temp', '{}.shp'.format(os.path.split(thing_path)[-1])) arcpy.CopyFeatures_management(thing_path, name_temp) arcpy.MakeFeatureLayer_management(in_features=name_temp, out_layer=lyr_name) else: arcpy.MakeFeatureLayer_management(in_features=thing_path, out_layer=lyr_name) else: gp.AddMessage('input file is not a raster or vector format') arcpy.SaveToLayerFile_management(lyr_name, os.path.join(folder, 'temp', '{}.lyr'.format(os.path.split(thing_path)[-1])), "ABSOLUTE") add_layer = arcpy.mapping.Layer(os.path.join(folder, 'temp', '{}.lyr'.format(os.path.split(thing_path)[-1]))) arcpy.mapping.AddLayer(df, add_layer) arcpy.RefreshActiveView() arcpy.RefreshTOC()
def make_map(dir): prev_workspace = arcpy.env.workspace arcpy.env.workspace = dir #Make a Map Document try: mapList = arcpy.ListFiles("*.mxd") mxd_path = os.path.join(dir, mapList[0]) mxd = arcpy.mapping.MapDocument(mxd_path) data_frames = arcpy.mapping.ListDataFrames(mxd) data_frame = data_frames[0] fcs = arcpy.ListFeatureClasses() for f in fcs: out_layer = f[:-4] out_layer_file = out_layer + ".lyr" arcpy.MakeFeatureLayer_management(f, out_layer) arcpy.SaveToLayerFile_management(out_layer, out_layer_file) layer_object = arcpy.mapping.Layer(f) arcpy.mapping.AddLayer(data_frame, layer_object) arcpy.RefreshTOC() project_map = map_document[:-4] + "Presentation.mxd" mxd.saveACopy(os.path.join(prev_workspace, project_map)) os.startfile(os.path.join(prev_workspace, project_map)) arcpy.env.workspace = prev_workspace del mxd except arcpy.AddMessage("\tPlease check inputs"): arcpy.GetMessages()
def mergePhotosNoText( inlist, outPath, year, poly, scale, document=r"C:\Workspace\Topo_work\mopoMerger_minimalist.mxd", site=True): """""" outname = os.path.join(outPath, '{0}_{1}.jpg'.format(year, scale)) mxd = arcpy.mapping.MapDocument(document) df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] ### change some text around ## mydict = {x.name: x for x in arcpy.mapping.ListLayoutElements(mxd)} ## mydict['year'].text = str(year) ## basequadtext = "{quad}, {state}\n" ## quadtext = "" ## for i in inlist: ## name = os.path.split(i)[1][:-4] ## stateusps = name[:2] ## state = statedict[stateusps.upper()] ## quad = ' '.join(x.capitalize() for x in name.split('_')[1].split(' ')) ## print quad ## quadtext += basequadtext.format(state=state, quad=quad) ## mydict["quadname"].text = quadtext ## ## if scale == '24k': ## mydict['minute'].text = mydict['minute'].text.format('7.5') ## elif scale == '62k': ## mydict['minute'].text = mydict['minute'].text.format('15') ## else: ## print 'wrong scale bitch' ## print 'here' for i, raster in enumerate(inlist): name = os.path.split(raster)[1][:-4] templayer = arcpy.MakeRasterLayer_management(raster, name) layerondisk = arcpy.SaveToLayerFile_management( templayer, r'C:\temp\temp{}.lyr'.format(name)) a = arcpy.mapping.Layer(r'C:\temp\temp{}.lyr'.format(name)) arcpy.mapping.AddLayer(df, a, 'AUTO_ARRANGE') df.displayUnits = "inches" #templayer = arcpy.MakeFeatureLayer_management(r'C:\temp2\temp_feature.shp',"test") #layerondisk = arcpy.SaveToLayerFile_management(templayer, r'C:\temp\site.lyr') # this will be an if clause to see what shape it is and what layer works best if site == True: a = arcpy.mapping.Layer(r'C:\temp\point_test.lyr') a.transparency = 10 #print a.symbologyType #a.transparency = 0 #a.replaceDataSource(r'C:\Workspace\topo_work\terracon_example.gdb\tester') arcpy.mapping.AddLayer(df, a, "TOP") arcpy.SelectLayerByAttribute_management(a, 'CLEAR_SELECTION') #df.elementHeight = 9 #df.elementWidth = 8 df.spatialReference = poly.spatialReference df.extent = poly.extent arcpy.mapping.ExportToJPEG( mxd, outname, resolution=300 ) #df,df_export_width=2400,df_export_height=2700,resolution=300 )
def create_huc8_layers (outputFolder, fieldList, functionList, symbologyList, layerNameList, network, huc8_shp, state): print "Calculating layers for HUC8s" fieldList = add_fields(fieldList, huc8_shp) dataListList = [[] for i in range(len(functionList))] layerPathList = [] clipLocation = huc8_shp huc8s_list = [row[0] for row in arcpy.da.SearchCursor(clipLocation, 'NAME')] for huc8 in huc8s_list: hucString = str(huc8) print '\n\nCalculating data for ' + hucString, if hucString == """Coeur d'Alene Lake""": hucString = """Coeur d''Alene Lake""" if hucString == """South Fork Coeur d'Alene""": hucString = """South Fork Coeur d''Alene""" if hucString == """Upper Coeur d'Alene""": hucString = """Upper Coeur d''Alene""" sqlString = (""""NAME" = """ + """'""" + hucString + """'""") tempArea = arcpy.MakeFeatureLayer_management(clipLocation, 'temp_huc8.shp', sqlString) tempAreaPath= os.path.join(outputFolder, "TempBorder.lyr") arcpy.SaveToLayerFile_management(tempArea, tempAreaPath) tempNetwork = arcpy.MakeFeatureLayer_management(network, 'TempNetworkFull') tempNetworkPath = os.path.join(outputFolder, "TempNetworkFull.lyr") arcpy.SaveToLayerFile_management(tempNetwork, tempNetworkPath) clippedRegion = clip_to_boundary(tempNetworkPath, tempAreaPath, outputFolder) for dataList, function in zip(dataListList, functionList): dataList.append(function(clippedRegion)) print ".", delete_layers([clippedRegion]) delete_layers([tempAreaPath]) delete_layers([tempNetworkPath]) for field, dataList in zip(fieldList, dataListList): update_huc(field, clipLocation, dataList) print "\n" layerPathList = make_layers(clipLocation, symbologyList, layerNameList, outputFolder) package_layers(layerPathList, outputFolder) delete_layers(layerPathList) delete_layers([clipLocation]) print "\nDone with HUC8s!"
def save_layer_file(inLyr, outLyrPath): """ Save the symbology of a layer into a layer file """ arcpy.SaveToLayerFile_management(inLyr, outLyrPath, "ABSOLUTE") return outLyrPath
def saveLayerFile(layer, name, out_dir): # create a feature layer arcpy.MakeFeatureLayer_management(layer, name) # directory and name of layer file out_layer_file = r'{}\{}.lyr'.format(out_dir, name) # save as a layer file arcpy.SaveToLayerFile_management(name, out_layer_file, "RELATIVE") # get access to layer file return out_layer_file
def createLayerFile(self): file_target = arcpy.CreateScratchName("Network.lyrx", "", "Folder", arcpy.env.scratchFolder) arcpy.SaveToLayerFile_management(in_layer=self.network.lyr(), out_layer=file_target) return file_target
def createLayerFromShapefile(Input_Path, name, Temporary_Output_Path): path_to_layer = Temporary_Output_Path + "\\" + name + "_layer.lyr" arcpy.MakeFeatureLayer_management(Input_Path, name) newlayer = arcpy.SaveToLayerFile_management(name, Input_Path, "ABSOLUTE") p = arcpy.mp.ArcGISProject("CURRENT") m = p.activeMap lyr = m.addDataFromPath(newlayer) getLayerStyle(name, lyr) lyr.visible = True
def dbf2shp(dbfFile,x_coords, y_coords, savedLayer, outShape, spRef, z_coords): # テンポラリなレイヤーファイルの指定 out_Layer = "dem_layer" # 投影法の設定 spRef = "D:/arcpy_work/Lidar_tool/point2raster/prj/JGD2000_xy9.prj" # dbfファイルからポイントレイヤーを生成 arcpy.MakeXYEventLayer_management(dbfFile, x_coords, y_coords, savedLayer, spRef, z_coords) # ポイントレイヤーを保存 arcpy.SaveToLayerFile_management(out_Layer, savedLayer)
def addImageToMxd(raster, mxdpath): """""" mxd = arcpy.mapping.MapDocument(mxdpath) df = arcpy.mapping.ListDataFrames(mxd, 'Layers')[0] name = os.path.split(raster)[1][:-4] templayer = arcpy.MakeRasterLayer_management(raster, name) layerondisk = arcpy.SaveToLayerFile_management( templayer, r'C:\temp\temp{}.lyr'.format(name)) a = arcpy.mapping.Layer(r'C:\temp\temp{}.lyr'.format(name)) arcpy.mapping.AddLayer(df, a, 'AUTO_ARRANGE')
def create_huc6_layers (outputFolder, fieldList, functionList, symbologyList, layerNameList, network, huc6_shp, state): print "Calculating layers for HUC6s" fieldList = add_fields(fieldList, huc6_shp) dataListList = [[] for i in range(len(functionList))] layerPathList = [] clipLocation = clip_area(huc6_shp, state, outputFolder) huc6s_list = [row[0] for row in arcpy.da.SearchCursor(clipLocation, 'NAME')] for huc6 in huc6s_list: print '\n\nCalculating data for ' + str(huc6), sqlString = (""""NAME" = """ + """'""" + str(huc6) + """'""") tempArea = arcpy.MakeFeatureLayer_management(clipLocation, 'temp_huc6.shp', sqlString) tempAreaPath= os.path.join(outputFolder, "TempBorder.lyr") arcpy.SaveToLayerFile_management(tempArea, tempAreaPath) tempNetwork = arcpy.MakeFeatureLayer_management(network, 'TempNetworkFull') tempNetworkPath = os.path.join(outputFolder, "TempNetworkFull.lyr") arcpy.SaveToLayerFile_management(tempNetwork, tempNetworkPath) clippedRegion = clip_to_boundary(tempNetworkPath, tempAreaPath, outputFolder) for dataList, function in zip(dataListList, functionList): if huc6 == "Missouri Headwaters": dataList.append(-1) else: dataList.append(function(clippedRegion)) print ".", delete_layers([clippedRegion]) delete_layers([tempAreaPath]) delete_layers([tempNetworkPath]) for field, dataList in zip(fieldList, dataListList): update_huc(field, clipLocation, dataList) print "\n" layerPathList = make_layers(clipLocation, symbologyList, layerNameList, outputFolder) package_layers(layerPathList, outputFolder) delete_layers(layerPathList) delete_layers([clipLocation]) print "\nDone with HUC6s!"
def txt2lyr(Location, txtFile, sr): #nameList = txtFile.split(".") mapName = txtFile.split(".")[-2] outLocation = Location outTable = mapName outLayer = mapName savedLayer = outLayer +'.lyr' arcpy.TableToTable_conversion(txtFile, outLocation, outTable) arcpy.MakeXYEventLayer_management(txtFile, "x", "y", outLayer, sr, "z") arcpy.SaveToLayerFile_management(outLayer, savedLayer)
def make_layer(output_folder, layer_base, new_layer_name, symbology_layer=None, is_raster=False, description="Made Up Description", file_name=None, symbology_field=None): """ Creates a layer and applies a symbology to it :param output_folder: Where we want to put the layer :param layer_base: What we should base the layer off of :param new_layer_name: What the layer should be called :param symbology_layer: The symbology that we will import :param is_raster: Tells us if it's a raster or not :param description: The discription to give to the layer file :return: The path to the new layer """ new_layer = new_layer_name if file_name is None: file_name = new_layer_name.replace(' ', '') new_layer_save = os.path.join(output_folder, file_name.replace(' ', '')) if not new_layer_save.endswith(".lyr"): new_layer_save += ".lyr" if is_raster: try: arcpy.MakeRasterLayer_management(layer_base, new_layer) except arcpy.ExecuteError as err: if get_execute_error_code(err) == "000873": arcpy.AddError(err) arcpy.AddMessage( "The error above can often be fixed by removing layers or layer packages from the Table of Contents in ArcGIS." ) raise Exception else: raise arcpy.ExecuteError(err) else: if arcpy.Exists(new_layer): arcpy.Delete_management(new_layer) arcpy.MakeFeatureLayer_management(layer_base, new_layer) if symbology_layer: arcpy.ApplySymbologyFromLayer_management(new_layer, symbology_layer) if not os.path.exists(new_layer_save): arcpy.SaveToLayerFile_management(new_layer, new_layer_save, "RELATIVE") new_layer_instance = arcpy.mapping.Layer(new_layer_save) new_layer_instance.description = description new_layer_instance.save() return new_layer_save
def symbolize_labels(newLayer, filePath, symbology, outputFolder): # Adds proper symbology to the reference labels shapefile. # Because labels aren't technically 'symbology', more work has to be done to transfer them over. # Code partially adapted from Ian Broad. http://ianbroad.com/download/script/UpdateLayerProperties.py # Save the layer file so it is accessible later arcpy.SaveToLayerFile_management(newLayer, filePath) # Initialize the map document and data frame mxd = arcpy.mapping.MapDocument(os.path.join(symbology_folder, "Summary_Labels.mxd")) df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] # Add the current data to the new map newLayer = arcpy.mapping.Layer(filePath) arcpy.mapping.AddLayer(df, newLayer, "BOTTOM") # Save all necessary data about the current layers so it can be restored later layer_file_object = arcpy.mapping.Layer(symbology) original_fc_name = str(layer_file_object.name) input_layer_object = arcpy.mapping.ListLayers(mxd, newLayer)[0] input_fc_name = str(input_layer_object.datasetName) input_fc_toc_name = str(input_layer_object.name) input_fc_workspace = str(input_layer_object.workspacePath) # Set the new worspace type based off of the workspace ID workspace_id = str(arcpy.Describe(input_fc_workspace).workspaceFactoryProgID) if workspace_id == "esriDataSourcesGDB.AccessWorkspaceFactory.1": workspace_type = "ACCESS_WORKSPACE" elif workspace_id == "esriDataSourcesGDB.FileGDBWorkspaceFactory.1": workspace_type = "FILEGDB_WORKSPACE" elif workspace_id == "esriDataSourcesGDB.SdeWorkspaceFactory.1": workspace_type = "SDE_WORKSPACE" else: workspace_type = "SHAPEFILE_WORKSPACE" # Update the layer to hold necessary labels and symbology arcpy.mapping.UpdateLayer(df, input_layer_object, layer_file_object, False) refocus_layer = arcpy.mapping.ListLayers(mxd, original_fc_name)[0] refocus_layer.replaceDataSource(input_fc_workspace, workspace_type, input_fc_name) refocus_layer.name = input_fc_toc_name arcpy.RefreshTOC() # Create an image file of the area for reference arcpy.Delete_management(arcpy.mapping.ListLayers(mxd, "", df)[0]) ext = input_layer_object.getExtent() df.extent = ext arcpy.mapping.ExportToJPEG(mxd, os.path.join(outputFolder, "ReferenceMap.jpeg"), df, 5000, 5000, 150) # Return the new layer, that now has correct labels and symbology return input_layer_object
def map_maker(self,resolution,gridshape,SpRf,outIDWname,out_Layer,Mapdir,mxdpath,rastername): radius = float(resolution) * 2.5 ################################################################################ arcpy.CheckOutExtension("Spatial") print ("Creating interpolated raster file") #self.outIDWname = os.path.join(self.Mapdir, self.rastername) try: arcpy.DefineProjection_management(gridshape,SpRf) outIDW = Idw(gridshape, "PROB", resolution, 2, RadiusFixed(radius)) outIDW.save(outIDWname) except: print arcpy.GetMessages(2) print ("Interpolation complete") print ("------------------------------------------------------") arcpy.CheckInExtension("Spatial") ################################################################################ print ("Creating JPEG") templyr = out_Layer+"_temp" outLYR = out_Layer+".lyr" ADDLYR = os.path.join(Mapdir,outLYR) Jname = out_Layer+".jpg" outJPEG = os.path.join(Mapdir,Jname) ################################################################################ try: """To create JPEGS, all rasters must be saved as .lyr files with a symbology <- creates a temp layer first""" arcpy.MakeRasterLayer_management(rastername, templyr) #Saves the layer from the raster arcpy.SaveToLayerFile_management(templyr,outLYR,"ABSOLUTE") #Opens the .mxd file that was created with the layout desired mxd = arcpy.mapping.MapDocument(mxdpath) #Lists all dataframes in the mxd file.. the [0] takes the first one #listed dataf = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] #Adds the .lyr file to the dataframe addLayer = arcpy.mapping.Layer(ADDLYR) #Adds and arranges the .lyr file to the layout arcpy.mapping.AddLayer(dataf,addLayer,"AUTO_ARRANGE") #Exports the mxd layout with the new layer to a JPEG arcpy.mapping.ExportToJPEG(mxd, outJPEG) del mxd except: print arcpy.GetMessages() return outJPEG
def createXYfeatureFromTable(erupcion): in_table = "C:/Users/Humberto Ariza/OneDrive - Universidad de Los Andes/Tesis VF/code/arcmap/gdbs/tesis" + erupcion + ".gdb/cleanTable" x_coords = "UTMX" y_coords = "UTMY" z_coords = "Erupcion" out_layer = erupcion + "_layer" saved_layer = "C:/Users/Humberto Ariza/OneDrive - Universidad de Los Andes/Tesis VF/code/arcmap/layers/" + erupcion + "/" + out_layer spRef = arcpy.SpatialReference(2135) ## WKID CODE # Make the XY event layer... arcpy.MakeXYEventLayer_management(in_table, x_coords, y_coords, out_layer, spRef, z_coords) # Save to a layer file arcpy.SaveToLayerFile_management(out_layer, saved_layer) print "Paso 5: Terminado"
def pointsToShape(file): csvFile = file in_x_field = "Longitude" in_y_field = "Latitude" out_layer = "Timeframe" spatial_reference = 4326 csvLayer = arcpy.MakeXYEventLayer_management(csvFile, in_x_field, in_y_field, out_layer, spatial_reference) # arcpy.CopyFeatures_management(csvLayer,"shapenamesd.shp") arcpy.SaveToLayerFile_management(csvLayer, "shapename.shp") print("done")
def ZonalStasAsTable(fc, DBF_dir, raster, zoneField): for row in arcpy.SearchCursor(fc): lyr = "Zone_{0}_lyr".format(row.OBJECTID) tempTable = DBF_dir + os.sep + "zone_{0}.dbf".format(row.OBJECTID) arcpy.MakeFeatureLayer_management( fc, lyr, "\"OBJECTID\" = {0}".format(row.OBJECTID)) print "Creating layer {0}".format(lyr) out_layer = DBF_dir + os.sep + lyr + ".lyr" arcpy.SaveToLayerFile_management(lyr, out_layer, "ABSOLUTE") print "Saved layer file" arcpy.gp.ZonalStatisticsAsTable_sa(out_layer, zoneField, raster, tempTable, "DATA", "ALL") print "Populating zonal stats for {0}".format(lyr) del row, lyr
def layer_meta_archive(input, clip_val, clip_text): print("Archiving MapPLUTO {}".format(clip_text)) print("Creating in-memory layer.") arcpy.MakeFeatureLayer_management(input, input + prod_version + clip_val) print("Saving layer to appropriate path.") arcpy.SaveToLayerFile_management(input + prod_version + clip_val, os.path.join(m_arch_path, input.replace("_UNLCIPPED", "") + " " + prod_version + " " + release_date_text + " - {}".format(clip_text))) print("Exporting metadata xmls to appropriate path") arcpy.ExportMetadata_conversion(input, translator, os.path.join(m_arch_path, input.replace("_UNLCIPPED", "") + " " + prod_version + " " + release_date_text + " - {}.lyr.xml".format(clip_text))) print("Applying appropriate symbology from previous export") arcpy.ApplySymbologyFromLayer_management(os.path.join(m_arch_path, input.replace("_UNLCIPPED", "") + " " + prod_version + " " + release_date_text + " - {}.lyr".format(clip_text)), layer_symb_path)