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]
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) print("Complete") #--------------------------------------------------------------------------------------------------------- #For use in the python window in ArcMap - this saves time if you have more than 2 comparisons, otherwise manually changing is faster. You have to change the .lyr name and the targets name when switching to tidal and total. If you've already separated te vetors into individual data frames - then do not include line 46 and make the target layer more specific ex: 'Vectors_Erosion_Dune*', this will do a search through all the dataframes you have. #>>> import arcpy.mapping as mapping #>>> mxd = mapping.MapDocument("CURRENT") #>>> source = mapping.Layer(r"M:\01_NPS\01_Gateway\01_SHU\05_Projects\KingmanMills\KM_2012-2019\15_Layers\Dune_erosion.lyr") #>>> for df in mapping.ListDataFrames(mxd): #... if (df.name == 'ElevationChange'): #... targets = mapping.ListLayers(mxd,'Vectors_Erosion*',df) #... for layer in targets: #... mapping.UpdateLayer(df,layer,source,True)
print "Saving as %s" % backup_mxd #shutil.copy(mapdoc, backup_mxd) # update and insert layer main_df = mp.ListDataFrames(mxd)[1] main_lyrs = mp.ListLayers(mxd, "", main_df) for lyr in main_lyrs: lyr_name = lyr.name if "Sea" in lyr_name: lyr.transparency = 0 elif "Contours" in lyr_name: print "Updating %s" % lyr_name mp.UpdateLayer(main_df, lyr, ref_lyr) elif "Bathymetry" in lyr_name: print "Removing %s" % lyr_name mp.RemoveLayer(main_df, lyr) else: pass #print 'no' #save mapdoc mxd.save() #export map map_name = os.path.join(out_dir, mdoc_name) print "Exporting %s" % mapdoc mp.ExportToPNG(mxd, map_name, resolution=250)
import arcpy.mapping as ma mxd = ma.MapDocument("CURRENT") df = ma.ListDataFrames(mxd)[0] lyrs = ma.ListLayers(mxd, "IceUV*") for i in range(len(lyrs)): ma.UpdateLayer(df, lyrs[i], lyrs[-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 mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") df = mapping.ListDataFrames(mxd, "Crime")[0] updateLayer = mapping.ListLayers(mxd, "Crime Density by School District", df)[0] sourceLayer = mapping.Layer( r"E:\ArcPyStudy\Data\ArcpyBook\data\CrimeDensityGradSym.lyr") mapping.UpdateLayer(df, updateLayer, sourceLayer, True)
# Set up loop for adding raster layers to MXD for ras in rasList2: rasName2 = os.path.basename(ras[:-4]) if "Per" in rasName2: outLyr = outlyrDir + rasName2 + ".lyr" tmpLyr = outlyrDir + rasName2 rasProj = rasDir2 + rasName2 + "wbMerc.tif" 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
# 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")
###################################################################### ## 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":
# Check if there is yk_adp in the new layers. If there is adp will be labeled turn off the labels for sp if 'yk_Address_Points' in fc_list and 'Surveyed_Parcels' in fc_list: sp_lyr = mp.ListLayers(mxd, 'Surveyed_Parcels', df)[0] sp_lyr.showLabels = False # Change the symbology of select base map layers to match adjusted settings for l_path in gms_base_symb_change: lyr = mp.Layer(l_path) lyr_name = os.path.split(l_path)[1].split('.')[0] map_lyr = mp.ListLayers(mxd, lyr_name, df) if len(map_lyr) == 0: continue mp.UpdateLayer(df, map_lyr[0], lyr) del lyr # Replace lyr data sources with project mdb's mxd.replaceWorkspaces(ATLAS_gdb, 'FILEGDB_WORKSPACE', working_mdb_path, 'ACCESS_WORKSPACE') mxd.replaceWorkspaces(yk_adp_GDB, 'FILEGDB_WORKSPACE', working_mdb_path, 'ACCESS_WORKSPACE') print 'Exporting Map' # Required variables base_name = os.path.split(f)[1].split('.')[0] mxd_out_file = os.path.join(out_directory, '{}.mxd'.format(base_name)) # MXD out path # Save files logic mxd.saveACopy(
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())