def loadLYR(self): ''' @param: self @brief: Carga el fichero lyr de simbología (GRADUATED_COLORS) :return: None ''' self.GRADUATED_COLORS = mapping.Layer(GRADUATED_COLORS_LYR_PATH)
def addlayertotoc(o): # Set up the dataframe to display the shapes mxd = am.MapDocument("CURRENT") # get the data frame df = am.ListDataFrames(mxd, "*")[0] # create a new layer newlayer = am.Layer(o) # add the layer to the map at the bottom of the TOC in data frame 0 ap.mapping.AddLayer(df, newlayer, "BOTTOM") ap.RefreshActiveView() ap.RefreshTOC() del mxd, df, newlayer
def getFile(self): ''' @param: self @brief: Obtiene los datos del MXD seleccionado @return: None ''' # Diálogo nativo para elegir fichero dlg = QFileDialog() dlg.setFileMode(QFileDialog.ExistingFile) # Solo mostrar archivos con extensión shp dlg.setFilter("shapefile (*.shp)") if dlg.exec_(): # Obtenemos la ruta del archivo filepath = map(str, list(dlg.selectedFiles()))[0] # Eliminamos las capas (que hayan) en los dataframes self.deleteLayers() # Mostramos la ruta en el label self.label_shp_path.setText(filepath) # Creamos la capa a partir de la ruta layer = mapping.Layer(filepath) # Añadimos la capa a los dataframes self.addLayer(layer) # Actualizamos la simbología de las capas del dataframe [ mapping.UpdateLayer(df, l, self.GRADUATED_COLORS) for df in self.dataframes for l in mapping.ListLayers(self.mxd, '', df) ] # Creamos una variable de clase que contendrá las capas self.layers = mapping.ListLayers(self.mxd) # Obtenemos los campos de la capa fieldnames = map(lambda x: x.name, arcpy.ListFields(layer.dataSource)) # print fieldnames # Limpiamos los valores que haya en los comboboxes [combo.clear() for combo in self.comboboxes] # Añadimos los valores de los campos del shapefile [combo.addItems(fieldnames) for combo in self.comboboxes] #print self.mxd, self.dataframes, self.layers # Activamos los checkboxes [check.setEnabled(True) for check in self.checkboxes]
def add_layer_to_mxd(self, filename): """ Method for applying symbology to the in-memory layer and adding it to a template MXD file for output :param str filename: Name of the final output file for adding to the application """ df = mapping.ListDataFrames(self.mxd, "") create_layer = mapping.Layer(filename) ApplySymbologyFromLayer_management( create_layer, os.path.join(self.output_location, "least_squares.lyr")) mapping.AddLayer(df[0], create_layer, "BOTTOM") self.output_image("idwout.jpg")
def publish_service(agol, service_name, mxd_template, layer_file): """Publishe the service.""" # Create an sddraft file from the mxd. sd_dir = TEMPFILE.mkdtemp() mxd_temp = MAP.MapDocument(mxd_template) mxd_temp.summary = service_name mxd_temp.tags = service_name layer = MAP.Layer(layer_file) MAP.AddLayer(mxd_temp.activeDataFrame, layer) mxd_temp.saveACopy(OS.path.join(sd_dir, '{}.mxd'.format(service_name))) mxd = MAP.MapDocument(OS.path.join(sd_dir, '{}.mxd'.format(service_name))) # Make the sd draft and enable feature server. sd_draft = make_sd_draft(mxd, service_name, sd_dir) # Stage the sddraft file. SERVER.StageService(sd_draft, OS.path.join(sd_dir, "drought.sd")) # Upload (publish) map service. id = agol.upload(OS.path.join(sd_dir, "drought.sd"), "US Drought", "Current US Drought Conditions.") agol.publish(id)
if success: AddMessage(STEP_6_STARTED) # Apply symbology try: ApplySymbologyFromLayer_management(in_layer=output_layer, in_symbology_layer=symbology_layer) except: AddWarning(WARNING_APPLY_SYMBOLOGY_FAILED) AddWarning(GetMessages(2)) AddMessage(STEP_6_FAILED) # Display try: current_map_document = mapping.MapDocument("CURRENT") data_frame = mapping.ListDataFrames(current_map_document, "Layers")[0] add_layer = mapping.Layer(output_layer) mapping.AddLayer(data_frame, add_layer, "AUTO_ARRANGE") AddMessage(STEP_6_FINISHED) except: AddWarning(WARNING_FAIL_TO_DISPLAY) AddWarning(GetMessages(2)) AddMessage(STEP_6_FAILED) # Clean up clean_up() AddMessage(SUCCESS if success else FAILURE) except ExecuteAbort: clean_up()
START THE THIRD PART OF SCRIPT --------------------------------------------------------------------------- """ print "Beginning third step of script processing" # Set up variables env.workspace = "F:\\NFIE_SI_2016\\groupProject\\workspace\\" mapDoc = "F:\\NFIE_SI_2016\\groupProject\\imgCreation.mxd" mxd = mp.MapDocument(mapDoc) rasDir2 = "F:\\NFIE_SI_2016\\groupProject\\postprocessOutput\\rasters\\composites\\" outlyrDir = "F:\\NFIE_SI_2016\\groupProject\\postprocessOutput\\rasters\\layers\\" # Source layers that will be used for symbology reference fldext_srcLyr = mp.Layer(outlyrDir + "fldext_source_stretch.lyr") wd_srcLyr = mp.Layer(outlyrDir + "wd_source_stretch.lyr") fv_srcLyr = mp.Layer(outlyrDir + "fv_source_stretch.lyr") crit_srcLyr = mp.Layer(outlyrDir + "crit_source_stretch.lyr") spatialRef = arcpy.SpatialReference( 3857) # 3857 is code for WGS_1984_Web_Mecator (auxiliary sphere) # Remove all current possible layers in the MXD for df in mp.ListDataFrames(mxd): for lyr in mp.ListLayers(mxd, "*", df): mp.RemoveLayer(df, lyr) # Set up raster list dirList2 = os.listdir(rasDir2)
__author__ = 'G Torres' # used shutil instead of saveACopy because it: # does not like having functions in arguments # does not like overwriting existing mxd with the same name # throws AttributeError if any of these two things happen import os import shutil import glob import arcpy.mapping as mp # reference layers ref_lyr = mp.Layer( "D:\LUIGI\OML\GIS Project Files\BASEMAP ILOILO CITY\Sea and Lakes.lyr") ins_lyr = mp.Layer( "D:\LUIGI\OML\GIS Project Files\BASEMAP ILOILO CITY\Bathymetric Contours (250m interval).lyr" ) # walk through directory and sub-dir dir_root = "D:\LUIGI\OML\GIS Project Files" out_dir = "D:\LUIGI\OML\JPEGS WORKING DRAFTS" backup_dir = "D:\LUIGI\OML\GIS Project Files\BACKUP MXD" count = 1 for root, dirs, files in os.walk(dir_root): # ignore .mxd files with keywords if 'GROUND TRUTH' in root: pass elif 'SCALE' in root: pass
except ImportError: print("can't find arcpy") import arcpy.mapping as mapping #--------------------------------------------------------------------------------------------- path = r'M:/01_NPS/01_Gateway/01_SHU/05_Projects/KingmanMills/KM_2012-2019/' mxd = mapping.MapDocument( path + "06_ArcMap\KM_VolumetricChange.mxd") #Mapping document print("Accesing " + mxd.title) vectorType = "Dune" #Type of anlaysis (Total, Dune, Tidal) user determined type = "Erosion" #Type of vector (Erosion or Deposition) user determined layerLoc = (path + "15_Layers/" + vectorType + "_" + type + ".lyr") source = mapping.Layer(layerLoc) #target = mapping.ListLayers(mxd,'Vectors_' + type + '*',df) print(source) #------------------------------------------------------------------------------------------ for df in mapping.ListDataFrames(mxd): if ( df.name == 'ElevationChange' ): #This is a user controlled variable - its whatever the dataframe you put the vectors into is called targets = mapping.ListLayers(mxd, 'Vectors_' + type + '*', df) for layer in targets: print("Updating " + layer.name) test = mapping.UpdateLayer( df, layer, source, True ) #make this a variable and call it in and see if its working print(test)
import arcpy.mapping as mapping mxd = mapping.MapDocument("CURRENT") df = mapping.ListDataFrames(mxd, "Crime")[0] refLayer = mapping.ListLayers(mxd, "SD_Stream", df)[0] insertLayer = mapping.Layer( r'C:\SIGS\work\moverte\SHP\Tehuacan_Cuicatlan.gdb\Linea_transmision') mapping.InsertLayer(df, refLayer, insertLayer, "BEFORE")
print title, description, author else: print "document doesn?t exist" #------------------------------------------------------------------------------- # ADD LAYER #------------------------------------------------------------------------------- import arcpy from arcpy import mapping mxd = mapping.MapDocument('CURRENT') df = mapping.ListDataFrames(mxd)[0] layer_path = mapping.ListLayers(mxd, "", df) layer = mapping.Layer(layer_path) layer = arcpy.GetParameter(0) position = arcpy.GetParameter(1) mapping.AddLayer(df, layer, position) #------------------------------------------------------------------------------- # DESCRIBE #------------------------------------------------------------------------------- import arcpy from arcpy import mapping ## layer_path = r"C:\Users\laboratorios\ELVLC\session1\castilla-leon\ALTIMETRIA.shp" layer_path = arcpy.GetParameter(0) desc = arcpy.Describe(layer_path)
# ---------------------------------------------------------------------------------------------------------------------- # Logic # Initial layer setup and prep startTime = time.time() # capture start time # Paths to layers that will be added structure_points_fc = os.path.join(ATLAS_gdb, 'Structure_Points') transport_polygons_fc = os.path.join(ATLAS_gdb, 'Transportation_Polygons') building_footprints_fc = os.path.join(ATLAS_gdb, 'Building_Footprints') surveyed_parcels_fc = os.path.join(ATLAS_gdb, 'Surveyed_Parcels') unsurveyed_parcels_fc = os.path.join(ATLAS_gdb, 'Unsurveyed_Tenured_Commissioners_Land') # Convert fc to layer and add a definition query where necessary print 'Converting feature classes to layers' print 'Converting structure points' structure_points_lyr = mp.Layer(structure_points_fc) print 'Converting Transportation Polygons' transport_polygons_lyr = mp.Layer(transport_polygons_fc) print 'Converting Building Footprints' building_footprints_lyr = mp.Layer(building_footprints_fc) print 'Converting Surveyed Parcels' surveyed_parcels_lyr = mp.Layer(surveyed_parcels_fc) print 'Converting Unsurveyed Parcels' unsurveyed_parcels_lyr = mp.Layer(unsurveyed_parcels_fc) print 'Converting Yellowknife address points' yk_adp_lyr = mp.Layer(yk_adp_fc)
# # Author: Eric # # Created: 05/04/2018 # Copyright: (c) Eric 2018 # Licence: <your licence> #------------------------------------------------------------------------------- # this script uses UpdateLayer() function to update the symbology of a layer # script runs only in ArcMap as it references currently loaded map data # import the module import arcpy.mapping as mapping # reference currently active map document to a variable mxd = mapping.MapDocument("CURRENT") # get a reference to "crime" dataframe df = mapping.ListDataFrames(mxd, "Crime")[0] # define the layer that will be updated updateLayer = mapping.ListLayers(mxd, "Crime Density by School District", df)[0] # define the layer that will be used to update the symbology sourceLayer = mapping.Layer(r"C:\ArcpyBook\data\CrimeDensityGradSym.lyr") # call the UpdateLayer() function to update the symbology # True is used for updating symbology only, not properties mapping.UpdateLayer(df, updateLayer, sourceLayer, True)
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Eric # # Created: 04/04/2018 # Copyright: (c) Eric 2018 # Licence: <your licence> #------------------------------------------------------------------------------- # this script adds layers to a map using the AddLayer function # script only runs in ArcMap as it references currently loaded map documents # import the module import arcpy.mapping as mapping # reference the currently active document mxd = mapping.MapDocument("CURRENT") # get a reference to the "Crime" dataframe df = mapping.ListDataFrames(mxd)[0] # create a layer object that references a Layer file layer = mapping.Layer(r"C:\ArcpyBook\data\School_Districts.lyr") # add the layer to the dataframe mapping.AddLayer(df, layer, "AUTO_ARRANGE")
__author__ = 'G Torres' # used shutil instead of saveACopy because it: # does not like having functions in arguments # does not like overwriting existing mxd with the same name # throws AttributeError if any of these two things happen import os import shutil import glob import arcpy.mapping as mp # reference layers ref_lyr = mp.Layer("D:\LUIGI\OML\GIS Project Files\BASEMAP DAVAO ORIENTAL\Sea.lyr") ins_cont = mp.Layer("D:\LUIGI\OML\GIS Project Files\BASEMAP DAVAO ORIENTAL\Contours.lyr") ins_bathy = mp.Layer("D:\LUIGI\OML\GIS Project Files\BASEMAP DAVAO ORIENTAL\Bathymetric Contours (1000m intervals).lyr") # walk through directory and sub-dir dir_root = "D:\LUIGI\OML\GIS Project Files" out_dir = "D:\LUIGI\OML\JPEGS WORKING DRAFTS" backup_dir = "D:\LUIGI\OML\GIS Project Files\BACKUP MXD" count = 1 for root, dirs, files in os.walk(dir_root): # ignore .mxd files with keywords if 'GROUND TRUTH' in root: pass elif 'SCALE' in root: pass elif 'BACKUP' in root:
import arcpy.mapping as mapping mxd = mapping.MapDocument("CURRENT") df = mapping.ListDataFrames(mxd, "Crime")[0] updateLayer = mapping.ListLayers(mxd, "Prov_indBuildingsTwo", df)[0] sourceLayer = mapping.Layer( r'C:\EsriTraining\PythEveryone\PythonInArcGIS\NewTest.lyr') mapping.UpdateLayer(df, updateLayer, sourceLayer, False)
def makeMaps(rast, name): fullrast = os.path.join(rootdir, rast) if os.path.isfile(fullrast): #cropAccList = [("alf", "Alfalfa"), ("dry", "Beans"), ("cot", "Cotton"), ("cor", "Corn"), # ("pea", "Peas"), ("sil", "Corn Silage"), ("soy", "Soybeans"), ("wht", "Wheat")] #yieldStabList = [("level", "Yield Level"), ("_stab", "Yield Stability"), ("t_var", "Temporal Variance")] mxd = mapping.MapDocument(MXD) # get empty arcgis file df = mapping.ListDataFrames(mxd, "*")[0] for elm in mapping.ListLayoutElements( mxd, "TEXT_ELEMENT" ): # loop through the elements in the mxd and set them print "element: ", elm.name if elm.name == "Title": elm.text = "SALUS simulated VARIABLE, " + SC #if elm.name == "Unstable": # elm.elementPositionX = -5 #if elm.name == "total_area": # elm.elementPositionX = -5 layer = mapping.Layer(fullrast) # add the raster layer to the mxd mapping.AddLayer(df, layer, "TOP") arcpy.RefreshTOC() # refresh arcpy.RefreshActiveView() # Load the symbology layer (from a file or create one from the raster on the fly) #lyrname = SC + "_" + name ## Execute MakeFeatureLayer (save raster to lyr symbology file) ##arcpy.MakeRasterLayer_management(rast, lyrname, rootdir) #outlyr = rast.replace(".tif",".tif.lyr") outlyr = "mi_SC3_endvalue.tif.lyr" outlyr = os.path.join(lyr_folder, outlyr) sym_lay = mapping.Layer( outlyr ) # lyrname (using lines above) # or I can skip the line above and call the full path name (if lyr file is already made) lay_name = "Variable (units)" #mapping.AddLayer(df, layer, "TOP") updateLayer = mapping.ListLayers(mxd, "", df)[0] update_layer(df, updateLayer, sym_lay, True) apply_sym( updateLayer, sym_lay ) # added symbology_only = True so that the layer becomes classified (symbology)?? updateLayer.name = lay_name print "Added layer." #style_stab = mapping.ListStyleItems("USER_STYLE", "Legend Items")[0] legend = mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")[ 0] # updates all legend items to the chosen style for lyr in legend.listLegendItemLayers(): #[:3]: # legend.updateItem(lyr, style_stab) print "in legend: ", lyr.name if "States" in lyr.name or "Counties" in lyr.name: print "states is in legend" legend.removeItem(lyr) ############## endvarlist = ["avgGWAD", "avgCWAD"] for var in endvarlist: name = var + "_" + name for lyr in mapping.ListLayers( mxd, "", df)[:-1]: # -1 to avoid boundary layer lyr.visible = True print "layer name: ", lyr.name # change the symbology value field if lyr.symbologyType == "RASTER_CLASSIFIED": #, then create a variable reference to the RasterClassifiedSymbology class for that layer (lyrSymbolClass = lyr.symbology) print "RASTER IS CLASSIFIED" lyr.symbology.valueField = var # first value is the minimum #lyr.symbology.classBreakValues = [1, 60, 118, 165, 255] # one less label than the classBreakValues #lyr.symbology.classBreakLabels = ["1 to 60", "61 to 118", # "119 to 165", "166 to 255"] #lyr.symbology.classBreakDescriptions = ["Class A", "Class B", # "Class C", "Class D"] # lyr.symbology.excludedValues = '0' #name_temp = lyr.name #name = "{}.jpg".format(name_temp.replace(" ", "_")) arcpy.RefreshTOC() # refresh the TOC and active view arcpy.RefreshActiveView() outjpeg = os.path.join(outdir, name) mapping.ExportToJPEG(mxd, outjpeg, "PAGE_LAYOUT", resolution=300, jpeg_quality=100) #export to jpeg lyr.visible = False # switch off layer arcpy.RefreshTOC() # refresh again arcpy.RefreshActiveView() print "Created jpeg's of layers." # Save a copy of the mxd with the layer in it to the MXDs directory new_mxd_name = name + ".mxd" new_mxd = os.path.join(newMXDdir, new_mxd_name) arcpy.RefreshTOC() # refresh again arcpy.RefreshActiveView() mxd.saveACopy(new_mxd) ################## # Save the mapp and its data to a single compressed .mpkx file #MPK_name = name + ".mpk" #MPK_name = os.path.join(MPKdir, MPK_name) #print new_mxd #print MPK_name #arcpy.PackageMap_management(new_mxd, MPK_name, "PRESERVE", "CONVERT_ARCSDE", "#", "ALL") # crashes the script :( del mxd del df print "Done with ", rast print arcpy.Delete_management("in_memory") else: print "This raster does not exist:", fullrast
import arcpy.mapping as mapping mxd = mapping.MapDocument("CURRENT") df = mapping.ListDataFrames(mxd, "Crime")[0] updateLayer = mapping.ListLayers(mxd, "Prov_indBuildings", df)[0] sourceLayer = mapping.Layer( r'C:\EsriTraining\PythEveryone\PythonInArcGIS\RhodeIsland.gdb\Prov_indBuildingsTwo' ) mapping.UpdateLayer(df, updateLayer, sourceLayer, True)
import arcpy import arcpy.da as da import arcpy.mapping as harta arcpy.env.workspace = "t:/IE/bd_ro.mdb" arcpy.env.overwriteOutput = True tab_inj = arcpy.GetParameterAsText(0) tab_ind = arcpy.GetParameterAsText(1) dh = harta.MapDocument("CURRENT") df = harta.ListDataFrames(dh, "Layers")[0] ljt = harta.Layer(tab_inj) ljt.showLabels = True harta.AddLayer(df, ljt, "TOP") llt = harta.Layer(tab_ind) harta.AddLayer(df, llt, "TOP") listJud = [rand[0] for rand in da.SearchCursor("judTab", ("sj"))] for jud in listJud: arcpy.SelectLayerByAttribute_management(ljt, "NEW_SELECTION", "sj='" + jud + "'") arcpy.Clip_analysis(llt, ljt, "tabClip") arcpy.SelectLayerByAttribute_management(ljt, "CLEAR_SELECTION") listSeg = [rd[0] for rd in da.SearchCursor("tabClip", ("SHAPE@LENGTH"))] sl = sum(listSeg) crs = da.UpdateCursor(ljt, ("Lungime"), "sj='" + jud + "'") rand = crs.next()
print "Titulo: " + mxd.title + " Autor:" + mxd.author print mxd.summary #------------------------------------------------------------------------------- # -------- showing how to refresh the map after adding a new layer ------- #------------------------------------------------------------------------------- import arcpy import arcpy.mapping as map #Definiction of variables ruta = 'CURRENT' #reference to the current project mxd = map.MapDocument(ruta) #returns the MapDocument mapa = map.ListDataFrames(mxd)[0] #returns the first dataframe within the MapDocument #Layer reference accordind a specific path capa = map.Layer(r'E:\DAS\2016-2017\datos\castilla-leon\MUNICIPIO.shp') #Add the new layer map.AddLayer(mapa,capa) #Refreshing of the TOC and the active view arcpy.RefreshActiveView arcpy.RefreshTOC #------------------------------------------------------------------------------- # -------- dataframe access ------- #------------------------------------------------------------------------------- #Import modules import arcpy import arcpy.mapping as map try:
## pass for Bfc in BuildingFCs: BfcID = str(Bfc.split("_")[2]) for Officialfc in OfficialFishnetFCs: OfficialfcID = str(Officialfc.split("_")[2]) for RMSHDfc in RMSHDFishnetFCs: RMSHDfcID = str(RMSHDfc.split("_")[2]) for Cfc in CityFCs: CfcID = str(Cfc.split("_")[2]) if BfcID == OfficialfcID and BfcID == RMSHDfcID and BfcID == CfcID: ## arcpy.AddMessage("City Code" + BfcID + OfficialFfcID + RMSHDFfcID) InputBuildingLayer_temp = map.Layer(Bfc) InputOfficialFishnetLayer_temp = map.Layer( Officialfc) InputRMSHDFishnetLayer_temp = map.Layer(RMSHDfc) InputCityLayer_temp = map.Layer(Cfc) map.AddLayer(df, InputCityLayer_temp, "TOP") map.AddLayer(df, InputOfficialFishnetLayer_temp, "TOP") map.AddLayer(df, InputBuildingLayer_temp, "TOP") map.AddLayer(df, InputRMSHDFishnetLayer_temp, "TOP") RMSHDFishnetLayer = map.ListLayers(mxd, "", df)[0] BuildingLayer = map.ListLayers(mxd, "", df)[1] OfficialFishnetLayer = map.ListLayers(mxd, "",
# # Created: 04/04/2018 # Copyright: (c) Eric 2018 # Licence: <your licence> #------------------------------------------------------------------------------ # this script uses the InsertLayer() function to add a layer to a map doc # this function provides more control to where a layer is added within a data frame # compared to AddLayer() function. InsertLayer() uses a reference layer that places # the added layer below or above the reference layer. # script only runs in ArcMap as it references currently loaded map data # importing the modules import arcpy.mapping as mapping # reference currently active document mxd = mapping.MapDocument("CURRENT") # reference the crime data frame df = mapping.ListDataFrames(mxd, "Crime")[0] # define reference layer refLayer = mapping.ListLayers(mxd, "Burglaries*", df)[0] # define the layer to be inserted relative to the reference layer insertLayer = mapping.Layer( r"C:\ArcpyBook\data\CityOfSanAntonio.gdb\Crimes2009") # insert the layer into the dataframe mapping.InsertLayer(df, refLayer, insertLayer, "BEFORE")
if (df.name == 'Crime'): layers = mapping.ListLayers(mxd, 'Crime Density by School District', df) for lyr in layers: query = '"NAME"=\'Lackland ISD\'' lyr.definitionQuery = query df.extent = lyr.getExtent() # 8 添加、插入图层到地图文档 # (1)添加图层 import arcpy.mapping as mapping mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") df = mapping.ListDataFrames(mxd)[0] layer = mapping.Layer( r"E:\ArcPyStudy\Data\ArcpyBook\data\School_Districts.lyr") mapping.AddLayer(df, layer, "AUTO_ARRANGE") # (2)插入图层 import arcpy.mapping as mapping mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") df = mapping.ListDataFrames(mxd, "Crime")[0] refLayer = mapping.ListLayers(mxd, "Burg*", df)[0] # 指定图层 insertLayer = mapping.Layer( r"E:\ArcPyStudy\Data\ArcpyBook\data\CityOfSanAntonio.gdb\Crimes2009") mapping.InsertLayer(df, refLayer, insertLayer, "BEFORE") # 9 更新图层的符号系统 import arcpy.mapping as mapping
disfinal = soilRaster + redis disfinal.save(outPut + "/disfin") dismap = RemapValue([[1, 1], [2, 1], [11, 0], [12, 1]]) arcpy.SetProgressorLabel( "The progress is recalssify disfinal Raster, please wait for several minutes..." ) final = Reclassify(disfinal, "Value", dismap) arcpy.SetProgressorLabel( "The progress is saving final Raster, please wait for several minutes...") final.save(outPut + "/fin") #---------------------------------------Pretreatment to Extrate regions' anea----------------------------------------------# env.workspace = outPut mxd = mapping.MapDocument("CURRENT") df = mapping.ListDataFrames(mxd, "Layers")[0] refLayer = mapping.ListLayers(mxd, "HWSD*", df)[0] fin = mapping.Layer(r"fin") mapping.InsertLayer(df, refLayer, fin, "BEFORE") #--------------------------------------To extrate suitalbe reginons' area in China----------------------------------------# # Execute SelectLayerByAttribute arcpy.SelectLayerByAttribute_management("fin", "NEW_SELECTION", "\"VALUE\" =0") # Execute RasterToPolygon arcpy.RasterToPolygon_conversion("fin", "zones.shp", "NO_SIMPLIFY", "value") # Execute IntersectAnalysis arcpy.Intersect_analysis(["zones.shp", input1], "Intersect", "ALL", "", "") # Execute ConversationReference arcpy.DefineProjection_management( "Intersect.shp", "PROJCS['Sphere_Aitoff',GEOGCS['GCS_Sphere',DATUM['D_Sphere',SPHEROID['Sphere',6371000.0,0.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Aitoff'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],UNIT['Meter',1.0]]" ) # Execute AddFileld arcpy.CalculateAreas_stats("Intersect.shp", "IntersectAreaField.shp")
__author__ = 'G Torres' # used shutil instead of saveACopy because it: # does not like having functions in arguments # does not like overwriting existing mxd with the same name # throws AttributeError if any of these two things happen import os import shutil import glob import arcpy.mapping as mp # reference layer ref_lyr = mp.Layer("D:\LUIGI\OML\GIS Project Files\BASEMAP DAVAO CITY\Sea and Lakes.lyr") # walk through directory and sub-dir dir_root = "D:\LUIGI\OML\GIS Project Files" out_dir = "D:\LUIGI\OML\JPEGS WORKING DRAFTS" backup_dir = "D:\LUIGI\OML\GIS Project Files\BACKUP MXD" count = 1 for root, dirs, files in os.walk(dir_root): # work only on the large scale maps if "200000 SCALE" in root: mxd_list = glob.glob(root + '\*.mxd') lyr_list = glob.glob(root + '\*.lyr') for mapdoc in mxd_list: mdoc_name = os.path.basename(mapdoc).split('.')[0] print '%d. %s' % (count, mdoc_name)
###################################################################### ## UpdateMxd.py ## ## results script without pseudocode ###################################################################### ## Step 1 import arcpy.mapping as MAP mxd = MAP.MapDocument(r"C:\Student\PYTH\Map_production\CorvallisMeters.mxd") df = MAP.ListDataFrames(mxd)[0] ## Step 2 updateLayer = MAP.ListLayers(df, "ParkingMeters")[0] sourceLayer = MAP.Layer(r"C:\Student\PYTH\Map_production\ParkingMeters.lyr") MAP.UpdateLayer(df, updateLayer, sourceLayer, True) addLayer = MAP.Layer(r"C:\Student\PYTH\Map_production\Schools.lyr") MAP.AddLayer(df, addLayer) refLayer = MAP.ListLayers(df, "Schools")[0] ## This is the tricky step. The order of the arguments appears to be backwards. MAP.MoveLayer(df, refLayer, updateLayer, "BEFORE") ## Step 3 mxd.title = "Corvallis Meters Map" elemList = MAP.ListLayoutElements(mxd, "TEXT_ELEMENT") for elem in elemList: if elem.name == "Corvallis Meters":
import arcpy.mapping as mapping mxd = mapping.MapDocument("CURRENT") df = mapping.ListDataFrames(mxd)[0] layer = mapping.Layer( r'C:\Users\52222\Documents\03.Other\Work\JUANITO\Infor especifica\SIGS\Cuacnopalan.lyr' ) mapping.AddLayer(df, layer, "AUTO_ARRANGE")
# Purpose: # # Author: Eric # # Created: 05/04/2018 # Copyright: (c) Eric 2018 # Licence: <your licence> #------------------------------------------------------------------------------- # script uses UpdateLayer() function to update a number of layer properties, # and save a file to a layer file (.lyr) # import the module import arcpy.mapping as mapping # reference the currently active map document mxd = mapping.MapDocument("CURRENT") # get a reference to the crime data frame df = mapping.ListDataFrames(mxd, "Crime")[0] # define the layer that will be updated updateLayer = mapping.ListLayers(mxd, "Crimes2009", df)[0] # define the layer that will be used to update the properties sourceLayer = mapping.Layer(r"C:\ArcpyBook\data\BurglariesNoForcedEntry.lyr") # call the updatelayer() function to update the symbology mapping.UpdateLayer(df, updateLayer, sourceLayer, "False")
depth = "_Top" else: depth = "" key2 = key1 + depth # dictionary key for soil sample files descBoundary = arcpy.Describe(boundaryDict[key1]) fcExtent = descBoundary.extent # create layer file outIdwLyr = baseName + "_idwLyr" outSoilPointLyr = baseName + "_SoilPointLyr" ourBoundaryLyr = baseName + "_BoundaryLyr" arcpy.MakeRasterLayer_management(idwras, outIdwLyr, "", fcExtent, "1") arcpy.MakeFeatureLayer_management(boundaryDict[key1], ourBoundaryLyr, "", "", "") arcpy.MakeFeatureLayer_management(soilPointDict[key2], outSoilPointLyr, "", "", "") # create layer object addIdwLyr = mapping.Layer(outIdwLyr) addBoundaryLyr = mapping.Layer(ourBoundaryLyr) addSoilPointLyr = mapping.Layer(outSoilPointLyr) addSoilPointLyr.name = "Soil Sample" # create layer object for template layer idwTemp = mapping.Layer(idwRasTemplate) boundaryTemp = mapping.Layer(boundaryTemplate) soilSampTemp = mapping.Layer(soilSampTemplate) baseLayer = mapping.Layer(BaseMapLyr) addIdwLyr.transparency = 30 # apply layer template so as to render layers arcpy.mapping.UpdateLayer(df, addIdwLyr, idwTemp, True) arcpy.mapping.UpdateLayer(df, addBoundaryLyr, boundaryTemp, True) arcpy.mapping.UpdateLayer(df, addSoilPointLyr, soilSampTemp, True) # set symbology property for idw layers. Grouping values
__author__ = 'G Torres' # used shutil instead of saveACopy because it: # does not like having functions in arguments # does not like overwriting existing mxd with the same name # throws AttributeError if any of these two things happen import os import shutil import glob import arcpy.mapping as mp # reference layers ref_lyr = mp.Layer("D:\LUIGI\OML\GIS Project Files\BASEMAP ILOILO CITY\Sea and Lakes.lyr") cont_lyr = mp.Layer("D:\LUIGI\OML\GIS Project Files\BASEMAP ILOILO CITY\Bathymetric Contours.lyr") bathy_lyr = mp.Layer("D:\LUIGI\OML\GIS Project Files\BASEMAP ILOILO CITY\Bathymetry.lyr") # walk through directory and sub-dir dir_root = "D:\LUIGI\OML\GIS Project Files" out_dir = "D:\LUIGI\OML\JPEGS WORKING DRAFTS" backup_dir = "D:\LUIGI\OML\GIS Project Files\BACKUP MXD" count = 1 for root, dirs, files in os.walk(dir_root): # ignore .mxd files with keywords if 'GROUND TRUTH' in root: pass elif 'SCALE' in root: pass elif 'BACKUP' in root: pass