def addLayer(self, l): ''' @param: self @param l : Capa a añadir @brief: Añade la capa pasada a los dataframes :return: None ''' [mapping.AddLayer(df, l) for df in self.dataframes]
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)
layers = mapping.ListLayers(mxd) for lyr in layers: print(lyr) # (3)遍历地图文档所有数据框的所有图层并将所有图层依次添加到每个数据框 # 谨慎操作,循环次数过多,ArcGIS容易崩溃 import arcpy import arcpy.mapping as mapping mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") ldfs = mapping.ListDataFrames(mxd) for ldf in ldfs: print(ldf.name) layers = mapping.ListLayers(mxd) for lyr in layers: mapping.AddLayer(ldf, lyr, "AUTO_ARRANGE") arcpy.RefreshActiveView() arcpy.RefreshTOC() print(lyr.name) # (4)将第二个数据框的图层添加到第一个数据框 import arcpy.mapping as mapping mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") ldf1 = mapping.ListDataFrames(mxd)[0] ldf2 = mapping.ListDataFrames(mxd)[1] for lyr in ldf2: mapping.AddLayer(ldf1, lyr, "AUTO_ARRANGE") mxd.save( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new_AddLayer.mxd") # 语句有问题 print("添加完毕")
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, "", df)[2] CityLayer = map.ListLayers(mxd, "", df)[3] arcpy.ApplySymbologyFromLayer_management( BuildingLayer, "C:/gc_work/evl/LYRs/belgium/buildings.lyr")
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()
# now we want to make a map for each for lyr_name, lyr in lyrs.iteritems(): # the result stored in lyr is a result object, not a layer object # getOutput(0) gets the first (and only) output from the # MakeFeatureLayer commands, which happens to be a layer object lyr = lyr.getOutput(0) # open the blank mxd because we can't create them reasonably mxd = mapping.MapDocument(mxd_path) # have to get the first (and only) dataframe df = mapping.ListDataFrames(mxd)[0] # now we can add the layer object we pulled out above mapping.AddLayer(df, lyr) # let's save the modified mxd to a new file outmxd = os.path.join(map_dir, "{}_{}.mxd".format(fc_name, lyr_name)) print "Writing map doc {}".format(outmxd) mxd.saveACopy(outmxd) # clean up the mxd object del mxd ######################################################################### ### The below would be useful if it made any sense whatsoever as to ### what one needs to do with a sddraft file to setup the sd as ### required for the AWDB services. Without knowing how to do that, ### I've decided it is not worth automating at this time. ### If something changes and someone understands this, just uncomment and
ap.ProjectRaster_management(ras, rasProj, spatialRef) ap.MakeRasterLayer_management(rasProj, tmpLyr) ap.SaveToLayerFile_management(tmpLyr, outLyr) wrkLyr = mp.Layer(outLyr) # Update the symbology of the layers added if "fldext" in rasName2: wrkLyr.name = os.path.basename(rasProj[:-4]) mp.UpdateLayer(df, wrkLyr, fldext_srcLyr, True) elif "wd" in rasName2: wrkLyr.name = os.path.basename(rasProj[:-4]) mp.UpdateLayer(df, wrkLyr, wd_srcLyr, True) elif "fv" in rasName2: wrkLyr.name = os.path.basename(rasProj[:-4]) mp.UpdateLayer(df, wrkLyr, fv_srcLyr, True) elif "crit" in rasName2: wrkLyr.name = os.path.basename(rasProj[:-4]) mp.UpdateLayer(df, wrkLyr, crit_srcLyr, True) mp.AddLayer(df, wrkLyr) # Create the vector to loop through lyrVec = mp.ListLayers(df) # To be safe, start by hiding all of the layers for lyr in lyrVec: lyr.visible = False mxd.save() print "Processing Complete" ##END##
def CreateMXD(srcMXD, srcSHPDirs, targetDir, srcLyrDirs, srcGeo, srcStyleName, srcXlsxWB, srcSubjects, srcLogo): mxd = amp.MapDocument(srcMXD) mxdDF0 = amp.ListDataFrames(mxd, "Main")[0] mxdDF1 = amp.ListDataFrames(mxd, "Index")[0] prCode = srcGeo['prCode'] coCode = srcGeo['coCode'] ciCode = srcGeo['ciCode'] shpCity = srcSHPDirs['shpCity'] shpCounty = srcSHPDirs['shpCounty'] shpCounties = srcSHPDirs['shpCounties'] shpRegion = srcSHPDirs['shpRegion'] lyrCity = srcLyrDirs['lyrCity'] lyrCounty = srcLyrDirs['lyrCounty'] lyrCounties = srcLyrDirs['lyrCounties'] srcLyrCity = amp.Layer(lyrCity) srcLyrCounty = amp.Layer(lyrCounty) srcLyrCounties = amp.Layer(lyrCounties) mxdLayer00 = amp.Layer(shpRegion) mxdLayer10 = amp.Layer(shpCity) mxdLayer11 = amp.Layer(shpCounty) mxdLayer12 = amp.Layer(shpCounties) amp.AddLayer(mxdDF0, mxdLayer00, "TOP") amp.AddLayer(mxdDF1, mxdLayer12, "TOP") amp.AddLayer(mxdDF1, mxdLayer11, "TOP") amp.AddLayer(mxdDF1, mxdLayer10, "TOP") addLayer = amp.ListLayers(mxd, "", mxdDF1)[0] amp.UpdateLayer(mxdDF0, addLayer, srcLyrCity, True) addLayer = amp.ListLayers(mxd, "", mxdDF1)[1] amp.UpdateLayer(mxdDF0, addLayer, srcLyrCounty, True) addLayer = amp.ListLayers(mxd, "", mxdDF1)[2] amp.UpdateLayer(mxdDF0, addLayer, srcLyrCounties, True) addLayer = amp.ListLayers(mxd, "", mxdDF0)[0] fields = arcpy.ListFields(shpRegion) for field in fields: fieldName = field.name fieldCategory = fieldName[0:3] if fieldCategory in srcSubjects: lyrRegion = srcLyrDirs['lyrRegion'][fieldCategory] srcLyrRegion = amp.Layer(lyrRegion) amp.UpdateLayer(mxdDF0, addLayer, srcLyrRegion, True) if addLayer.supports("LABELCLASSES"): for labelClass in addLayer.labelClasses: labelClass.showClassLabels = True labelClass.expression = "\"<CLR red = '0' green = '0' blue = '0'><FNT size = '10' name = 'B Yekan'>\" & [areaCode] & \"</FNT></CLR>\"" addLayer.showLabels = True arcpy.RefreshActiveView() if addLayer.symbologyType == 'GRADUATED_COLORS': addLayer.symbology.valueField = fieldName labels = addLayer.symbology.classBreakLabels try: addLayer.symbology.classBreakLabels = createRanges(labels) except: print('Error in Symbology | %s' % fieldName) style0 = amp.ListStyleItems("USER_STYLE", "Legend Items", srcStyleName)[0] mxd_legend = amp.ListLayoutElements(mxd, "LEGEND_ELEMENT")[0] mxd_legend.title = "" mxd_legend.updateItem(addLayer, style0) for element in amp.ListLayoutElements(mxd, "PICTURE_ELEMENT"): elementName = element.name if elementName == 'Logo': element.sourceImage = srcLogo variableKeys = srcXlsxWB.sheet_by_index(0).row(0) colId = findInCellArray(variableKeys, fieldName) mapTitles = srcXlsxWB.sheet_by_index(0).cell_value(1, colId) for sheet in srcXlsxWB.sheets(): sheetName = sheet.name if sheetName == 'total': countryValue = sheet.cell_value(2, colId) elif sheetName == 'province': featureKeys = sheet.col(0) rowId = findInCellArray(featureKeys, makeStandard(prCode)) provinceName = sheet.cell_value(rowId, 1) provinceValue = sheet.cell_value(rowId, colId) elif sheetName == 'county': featureKeys = sheet.col(0) rowId = findInCellArray(featureKeys, makeStandard(coCode)) countyName = sheet.cell_value(rowId, 1) countyValue = sheet.cell_value(rowId, colId) elif sheetName == 'city': featureKeys = sheet.col(0) rowId = findInCellArray(featureKeys, makeStandard(ciCode)) cityName = sheet.cell_value(rowId, 1) cityName0 = cityName[0: len(cityName) - 1] cityName1 = cityName[len(cityName) - 1] if (isStrNumber(cityName1)): cityName = Utf8ToUnicode('منطقه ') + cityName1 + Utf8ToUnicode('شهر ') + cityName0 else: cityName = Utf8ToUnicode('شهر ') + cityName cityValue = sheet.cell_value(rowId, colId) elif sheetName == 'unit': unitText = sheet.cell_value(2, colId) for element in amp.ListLayoutElements(mxd, "TEXT_ELEMENT"): elementName = element.name if elementName == 'elLegend': mapTitles = maskTitle(" ".join(mapTitles.split())) defWidth = 8 element.fontSize = 16 element.text = mapTitles if element.elementWidth >= defWidth: words = mapTitles.split(' ') lines = [] line = [] tmp = '' itr = 0 while itr < len(words): word = words[itr] itr += 1 tmp += word + ' ' element.text = tmp line.append(word) if element.elementWidth >= defWidth: line.pop() lines.append(line) line = [] tmp = '' itr = itr - 1 if itr == len(words): count = 0 for l in lines: count += len(l) if count < len(words): lines.append(line) mapTitlesNew = '' for jj in range(0, len(lines)): lineStr = " ".join(lines[jj]) mapTitlesNew += lineStr if jj < len(lines) - 1: mapTitlesNew += "\n" element.text = mapTitlesNew elif elementName == 'elUnit' or elementName == 'elUnit2': element.text = unitText elif elementName == 'countryValue': element.text = round(countryValue,2) elif elementName == 'elProvinceTitle': element.text = Utf8ToUnicode('مناطق شهری استان ') + provinceName elif elementName == 'provinceValue': element.text = round(provinceValue,2) elif elementName == 'elCountyTitle': element.text = Utf8ToUnicode('مناطق شهری شهرستان ') + countyName elif elementName == 'countyValue': element.text = round(countyValue,2) elif elementName == 'elCityTitle': element.text = cityName elif elementName == 'cityValue': element.text = round(cityValue,2) try: mxd_name = targetDir['mxd'] + "//" + fieldName + ".mxd" mxd.saveACopy(mxd_name) except arcpy.ExecuteError: print(arcpy.GetMessages()) try: mxd_jpg_name = targetDir['jpg'] + fieldName + ".jpg" amp.ExportToJPEG(mxd, mxd_jpg_name, resolution=300) # multiprocessing.freeze_support() # p = multiprocessing.Process(target=test, args=(mxd.__getattribute__('filePath'), mxd_jpg_name)) # p.start() # p.join() except arcpy.ExecuteError: print(arcpy.GetMessages())
FishnetFCs = arcpy.ListFeatureClasses("MBFishnet*") CityFCs = arcpy.ListFeatureClasses("MBCity*") for Bfc in BuildingFCs: BfcID = str(Bfc.split("_")[1]) ## BfcOfficial = str(Bfc.split("_")[2]) for Ffc in FishnetFCs: FfcID = str(Ffc.split("_")[1]) for Cfc in CityFCs: CfcID = str(Cfc.split("_")[1]) if BfcID == FfcID and BfcID == CfcID: InputBuildingLayer_temp = map.Layer(Ffc) InputFishnetLayer_temp = map.Layer(Bfc) InputCityLayer_temp = map.Layer(Cfc) map.AddLayer(df, InputCityLayer_temp, "TOP") map.AddLayer(df, InputBuildingLayer_temp, "TOP") map.AddLayer(df, InputFishnetLayer_temp, "TOP") BuildingLayer = map.ListLayers(mxd, "", df)[0] FishnetLayer = map.ListLayers(mxd, "", df)[1] CityLayer = map.ListLayers(mxd, "", df)[2] arcpy.ApplySymbologyFromLayer_management( BuildingLayer, "C:/gc_work/evl/LYRs/buildings_belgium.lyr") arcpy.ApplySymbologyFromLayer_management( FishnetLayer, "C:/gc_work/evl/LYRs/fishnet_belgium.lyr") arcpy.ApplySymbologyFromLayer_management( CityLayer, "C:/gc_work/evl/LYRs/city.lyr")
for fc in fc_list: # Convert to lyr then apply symbology then add to map lyr = mp.Layer(lyr_style_guide[fc]) # For the below lyr types apply definition queries to remove non essential feature types # labeling is done here as well if lyr.name == 'Structure_Points': lyr.definitionQuery = "STRUCTURETYPE IN {}".format( str(tuple(['BTOWLIN', 'BPOHLIN', 'Antenna', 'Sign']))) if lyr.name == 'Transportation_Polygons': lyr.definitionQuery = "TRANSPORTATIONTYPE = 'RRWYLIN'" #arcpy.ApplySymbologyFromLayer_management(lyr, lyr_style_guide[lyr.name]) # This needs to stay below apply symbology layer because we're changing the lyr name mp.AddLayer(df, lyr, 'AUTO_ARRANGE') u_lyr = mp.ListLayers(mxd, lyr.name, df)[0] if u_lyr.name == 'Structure_Points': # moves structure points below the address range annotation to solve obscuring issue if len(mp.ListLayers( mxd, 'road_l_address_anno', df)) > 0: # check if road anno is actually in the map ref_lyr = mp.ListLayers(mxd, 'road_l_address_anno', df)[0] mp.MoveLayer(df, ref_lyr, u_lyr, 'AFTER') # Rename the unsurveyed parcels more concisely if u_lyr.name == 'Unsurveyed_Tenured_Commissioners_Land': u_lyr.name = 'Unsurveyed_Parcels' aug_counts[
#------------------------------------------------------------------------------- # -------- 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: #Definition of variables ruta = r'E:\DAS\2016-2017\temario_ingles\session1\theory\scripts\test.mxd'
#------------------------------------------------------------------------------- # 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")
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
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()
#------------------------------------------------------------------------------- # 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) print desc.name print desc.dataType print desc.path
## 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": elem.text = "Corvallis Parking Meters Inventory Report" #mxd.saveACopy(r"C:\Student\PYTH\Map_production\CorvallisMeters_ks.mxd")
arcpy.mapping.UpdateLayer(df, addBoundaryLyr, boundaryTemp, True) arcpy.mapping.UpdateLayer(df, addSoilPointLyr, soilSampTemp, True) # set symbology property for idw layers. Grouping values if addIdwLyr.symbologyType == "RASTER_CLASSIFIED": addIdwLyr.symbology.classBreakValues = ValueBreakDict[baseName.split("_")[-1]]["break"] addIdwLyr.symbology.classBreakLabels = ValueBreakDict[baseName.split("_")[-1]]["label"] addIdwLyr.save() # pan data frame to the extent of idw layer of interest mapExtent = addIdwLyr.getExtent() df.panToExtent(mapExtent) # set legend. Two legends are added in the mxd template legend1 = mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "Legend1")[0] legend2 = mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "Legend2")[0] legend1.autoAdd = True legend2.autoAdd = False mapping.AddLayer(df, addIdwLyr, "AUTO_ARRANGE") legend1.autoAdd = False legend2.autoAdd = True mapping.AddLayer(df, addSoilPointLyr, "AUTO_ARRANGE") legend1.autoAdd = False legend2.autoAdd = False mapping.AddLayer(df, addBoundaryLyr, "AUTO_ARRANGE") arcpy.mapping.AddLayer(df, baseLayer, "BOTTOM") # set name of legends legend1.title = baseName.split("_")[-1] + " Corrosion Rate (mils/year)" legend2.title = "" styleItem = mapping.ListStyleItems("ESRI.style", "Legend Items", "Horizontal Single Symbol Label Only")[0] # set layer style for lyr in legend1.listLegendItemLayers(): legend1.updateItem(lyr, styleItem) legend1.adjustColumnCount(3)
def main(): """ Runs the centrality tool. """ env.overwriteOutput = True # Enable overwritting CheckOutExtension("Network") # Success of the program through the six steps success = True # Inputs to the tool if len(argv) != INPUT_COUNT + 1: raise Exception("Invalid number of inputs") input_number = index() input_number.next() # Skip over sys.argv[0] inputs = {} inputs[INPUT_BUILDINGS] = argv[input_number.next()] inputs[POINT_LOCATION] = ("INSIDE" if argv[input_number.next()] == "true" else "CENTROID") inputs[INPUT_NETWORK] = argv[input_number.next()] inputs[COMPUTE_REACH] = argv[input_number.next()] == "true" inputs[COMPUTE_GRAVITY] = argv[input_number.next()] == "true" inputs[COMPUTE_BETWEENNESS] = argv[input_number.next()] == "true" inputs[COMPUTE_CLOSENESS] = argv[input_number.next()] == "true" inputs[COMPUTE_STRAIGHTNESS] = argv[input_number.next()] == "true" inputs[ID_ATTRIBUTE] = argv[input_number.next()] inputs[NODE_WEIGHT_ATTRIBUTE] = argv[input_number.next()] inputs[IMPEDANCE_ATTRIBUTE] = argv[input_number.next()] try: inputs[SEARCH_RADIUS] = float(argv[input_number.next()]) except: inputs[SEARCH_RADIUS] = INFINITE_RADIUS inputs[USE_NETWORK_RADIUS] = (argv[input_number.next()] == ON_THE_NETWORK_OPTION) try: inputs[BETA] = float(argv[input_number.next()]) except: raise Invalid_Input_Exception("Beta") inputs[NORMALIZE_RESULTS] = [measure for measure in argv[input_number.next()].split(";") if measure != "#"] inputs[OUTPUT_LOCATION] = argv[input_number.next()] inputs[OUTPUT_FILE_NAME] = argv[input_number.next()] inputs[ACCUMULATOR_ATTRIBUTES] = argv[input_number.next()] # Record the origin nodes for centrality measurements # This is important if the user selects a subset of the features to be origins selected_features = all_values_in_column(inputs[INPUT_BUILDINGS], inputs[ID_ATTRIBUTE]) # Clear selection if we got a layer file try: SelectLayerByAttribute_management(inputs[INPUT_BUILDINGS], "CLEAR_SELECTION") except: pass # Adjacency List table name node_locations_needed = (inputs[COMPUTE_STRAIGHTNESS] or not inputs[USE_NETWORK_RADIUS]) adj_dbf_name = ("%s_%s_%s_%s_%s_%s.dbf" % (ADJACENCY_LIST_NAME, basename(inputs[INPUT_BUILDINGS]), basename(inputs[INPUT_NETWORK]), inputs[ID_ATTRIBUTE], inputs[IMPEDANCE_ATTRIBUTE], inputs[ACCUMULATOR_ATTRIBUTES])).replace("#", "None") if len(adj_dbf_name) > MAX_FILE_NAME_LENGTH: AddWarning(WARNING_LARGE_ADJ_FILE_NAME) adj_dbf = join(inputs[OUTPUT_LOCATION], adj_dbf_name) # Output file names output_feature_class_name = feature_class_name(inputs[OUTPUT_FILE_NAME]) output_feature_class = "%s.shp" % join(inputs[OUTPUT_LOCATION], output_feature_class_name) # Create a feature class that is a copy of the input buildings try: AddMessage(INPUT_BUILDINGS_COPY_STARTED) CreateFeatureclass_management(out_path=inputs[OUTPUT_LOCATION], out_name=output_feature_class_name) CopyFeatures_management(in_features=inputs[INPUT_BUILDINGS], out_feature_class=output_feature_class) AddMessage(INPUT_BUILDINGS_COPY_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(INPUT_BUILDINGS_COPY_FAILED) success = False output_layer_name = layer_name(inputs[OUTPUT_FILE_NAME]) output_layer = "%s.lyr" % join(inputs[OUTPUT_LOCATION], output_layer_name) # If output has already been created, don't carry on if Exists(output_layer): AddWarning(WARNING_OUTPUT_ALREADY_EXISTS) success = False # We will convert polygon input buildings to point feature class buildings_description = Describe(output_feature_class) if buildings_description.shapeType == "Point": # Input buildings are already a point shape file inputs[INPUT_POINTS] = output_feature_class elif buildings_description.shapeType == "Polygon": # Input buildings need to be converted to point feature class point_feature_class_name = POINT_FEATURE_CLASS_NAME( basename(output_feature_class), inputs[POINT_LOCATION]) inputs[INPUT_POINTS] = "%s.shp" % join(inputs[OUTPUT_LOCATION], point_feature_class_name) # If FID is used as ID attribute, we need to change it since a point # shapefile will be in use if inputs[ID_ATTRIBUTE] == "FID": inputs[ID_ATTRIBUTE] = ORIGINAL_FID else: # Input buildings need to be either points or polygons raise Invalid_Input_Exception("Input Buildings") # Find the appropriate symbology layer for metric_index in range(len(METRICS)): if inputs[COMPUTE_REACH + metric_index]: first_metric = METRICS[metric_index] break symbology_layer_name = get_symbology_layer_name( buildings_description.shapeType, first_metric) symbology_layer = join(SYMBOLOGY_DIR, symbology_layer_name) def clean_up(): """ Removes all auxiliary files """ auxiliary_dir = join(inputs[OUTPUT_LOCATION], AUXILIARY_DIR_NAME) od_cost_matrix_layer = join(auxiliary_dir, OD_COST_MATRIX_LAYER_NAME) od_cost_matrix_lines = join(auxiliary_dir, OD_COST_MATRIX_LINES) temp_adj_dbf_name = "%s~.dbf" % adj_dbf_name[-4] temp_adj_dbf = join(inputs[OUTPUT_LOCATION], temp_adj_dbf_name) partial_adj_dbf = join(auxiliary_dir, PARTIAL_ADJACENCY_LIST_NAME) polygons = join(auxiliary_dir, POLYGONS_SHAPEFILE_NAME) raster = join(auxiliary_dir, RASTER_NAME) polygons_layer = join(auxiliary_dir, POLYGONS_LAYER_NAME) input_points_layer = join(auxiliary_dir, INPUT_POINTS_LAYER_NAME) for delete_path in [input_points_layer, polygons_layer, raster, polygons, partial_adj_dbf, temp_adj_dbf, od_cost_matrix_lines, od_cost_matrix_layer, auxiliary_dir]: delete(delete_path) try: """ Here we carry out the six steps of the tool """ # Step 1 if success: AddMessage(STEP_1_STARTED) # If necessary, convert input buildings to point feature class if buildings_description.shapeType == "Polygon": AddMessage(POINT_CONVERSION_STARTED) to_point_feature_class(output_feature_class, inputs[INPUT_POINTS], inputs[POINT_LOCATION]) AddMessage(POINT_CONVERSION_FINISHED) if Exists(adj_dbf): AddMessage(ADJACENCY_LIST_COMPUTED) if node_locations_needed: calculate_network_locations(inputs[INPUT_POINTS], inputs[INPUT_NETWORK]) AddMessage(STEP_1_FINISHED) else: try: compute_adjacency_list(inputs[INPUT_POINTS], inputs[INPUT_NETWORK], inputs[ID_ATTRIBUTE], inputs[IMPEDANCE_ATTRIBUTE], inputs[ACCUMULATOR_ATTRIBUTES], inputs[SEARCH_RADIUS], inputs[OUTPUT_LOCATION], adj_dbf_name) AddMessage(STEP_1_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_1_FAILED) success = False # Step 2 if success: AddMessage(STEP_2_STARTED) try: distance_field = trim("Total_%s" % inputs[IMPEDANCE_ATTRIBUTE]) accumulator_fields = set([trim("Total_%s" % accumulator_attribute) for accumulator_attribute in inputs[ACCUMULATOR_ATTRIBUTES].split( ";") if accumulator_attribute != "#"]) # Graph representation: dictionary mapping node id's to Node objects nodes = {} # The number of rows in |adj_dbf| directed_edge_count = int(GetCount_management(adj_dbf).getOutput(0)) graph_progress = Progress_Bar(directed_edge_count, 1, STEP_2) rows = UpdateCursor(adj_dbf) for row in rows: # Get neighboring nodes, and the distance between them origin_id = row.getValue(trim(ORIGIN_ID_FIELD_NAME)) destination_id = row.getValue(trim(DESTINATION_ID_FIELD_NAME)) distance = float(row.getValue(distance_field)) # Make sure the nodes are recorded in the graph for id in [origin_id, destination_id]: if not id in nodes: nodes[id] = Node() # Make sure that the nodes are neighbors in the graph if origin_id != destination_id and distance >= 0: accumulations = {} for field in accumulator_fields: accumulations[field] = float(row.getValue(field)) nodes[origin_id].add_neighbor(destination_id, distance, accumulations) nodes[destination_id].add_neighbor(origin_id, distance, accumulations) graph_progress.step() N = len(nodes) # The number of nodes in the graph if N == 0: AddWarning(WARNING_NO_NODES) success = False AddMessage(STEP_2_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_2_FAILED) success = False # Step 3 if success: AddMessage(STEP_3_STARTED) try: get_weights = inputs[NODE_WEIGHT_ATTRIBUTE] != "#" get_locations = node_locations_needed # Keep track of number nodes in input points not present in the graph point_not_in_graph_count = 0 input_point_count = int( GetCount_management(inputs[INPUT_POINTS]).getOutput(0)) node_attribute_progress = Progress_Bar(input_point_count, 1, STEP_3) rows = UpdateCursor(inputs[INPUT_POINTS]) for row in rows: id = row.getValue(inputs[ID_ATTRIBUTE]) if not id in nodes: point_not_in_graph_count += 1 continue if get_weights: setattr(nodes[id], WEIGHT, row.getValue(trim(inputs[NODE_WEIGHT_ATTRIBUTE]))) if get_locations: snap_x = row.getValue(trim("SnapX")) snap_y = row.getValue(trim("SnapY")) setattr(nodes[id], LOCATION, (snap_x, snap_y)) node_attribute_progress.step() if point_not_in_graph_count: AddWarning(WARNING_POINTS_NOT_IN_GRAPH(N, point_not_in_graph_count)) AddMessage(STEP_3_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_3_FAILED) success = False # Step 4 if success: AddMessage(STEP_4_STARTED) try: # Compute measures compute_centrality(nodes, selected_features, inputs[COMPUTE_REACH], inputs[COMPUTE_GRAVITY], inputs[COMPUTE_BETWEENNESS], inputs[COMPUTE_CLOSENESS], inputs[COMPUTE_STRAIGHTNESS], inputs[SEARCH_RADIUS], inputs[USE_NETWORK_RADIUS], inputs[BETA], inputs[NORMALIZE_RESULTS], accumulator_fields) AddMessage(STEP_4_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_4_FAILED) success = False # Step 5 if success: AddMessage(STEP_5_STARTED) try: # Make output layer MakeFeatureLayer_management(in_features=output_feature_class, out_layer=output_layer_name) # Save output layer SaveToLayerFile_management(output_layer_name, output_layer, "ABSOLUTE") # Use a test node to figure out which metrics were computed test_node_id = selected_features.pop() # Make sure the test node is in the graph while test_node_id not in nodes: test_node_id = selected_features.pop() test_node = nodes[test_node_id] measures = set([measure for measure in dir(test_node) if (measure in FINAL_ATTRIBUTES or is_accumulator_field(measure))]) # Add a field in the output layer for each computed metric for measure in measures: AddField_management(in_table=output_layer, field_name=trim(measure), field_type="DOUBLE", field_is_nullable="NON_NULLABLE") # Figure out the id field to use based on the type of input buildings if (buildings_description.shapeType == "Polygon" and inputs[ID_ATTRIBUTE] == ORIGINAL_FID): id_field = "FID" else: id_field = inputs[ID_ATTRIBUTE] # Fill the layer with the metric values write_progress = Progress_Bar(N, 1, STEP_5) layer_rows = UpdateCursor(output_layer) for row in layer_rows: id = row.getValue(id_field) for measure in measures: # If no value was computed for this node id, set value to 0 value = 0 if id in nodes and hasattr(nodes[id], measure): value = getattr(nodes[id], measure) row.setValue(trim(measure), value) layer_rows.updateRow(row) write_progress.step() # Save to toolbox output SetParameterAsText(OUTPUT_FEATURE_CLASS, output_feature_class) AddMessage(STEP_5_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_5_FAILED) success = False # Step 6 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()