def deleteExistingLegend(mxd): # Dictionary for the location of the legend in inches for each template coord 1- top left coord 2- bottom right # coord 1 coord 2 template_legend_XY = { '11X17': [(5.50, 3.25), (8.00, 0.50)], '17X11': [(13.75, 5.25), (16.5, 2.000)], '17X22': [(10.5, 3.25), (14.0, 0.5)], '22X17': [(18.74, 5.25), (21.5, 2.000)], '22X34': [(16.5, 3.25), (19.00, 0.5)], '34X22': [(30.75, 5.25), (33.5, 2.000)] } # Find all the elements that fall within the legend box for the specific template and delete or move them off map ex_text_element = mp.ListLayoutElements( mxd, 'TEXT_ELEMENT')[0] # extract text element for type testing purposes for ele in mp.ListLayoutElements(mxd): # Extract xy coordinates for the template legend legendRange = template_legend_XY[template_type] xMinMax = [legendRange[0][0], legendRange[1][0]] yMinMax = [legendRange[0][1], legendRange[1][1]] # determine if anchor point falls within the legend box for the template if (min(xMinMax[0], xMinMax[1]) < ele.elementPositionX < max(xMinMax[0], xMinMax[1])) and \ (min(yMinMax[0], yMinMax[1]) < ele.elementPositionY < max(yMinMax[0], yMinMax[1])): if not type(ele) == type( ex_text_element ): # text elements can't be groups so do this check first if ele.isGroup: # grouped cannot be deleted so move off the page ele.elementPositionX = 50.00 # New X coordinate for the group (inches) ele.elementPositionY = 5.00 # New Y coordinate for the group (inches) continue ele.delete( ) # Delete non grouped elements that fall within the legend area
def loadMXD(self): ''' @param: self @brief: Carga el archivo mxd :return: None ''' # Cargamos el mxd self.mxd = mapping.MapDocument(MXD_PATH) # Obtenemos los dataframes self.dataframes = mapping.ListDataFrames(self.mxd) # Activamos los componentes que están inactivos por defecto # (checkboxes, lineedit, ...) self.txt_title.setEnabled(True) self.check_scale.setEnabled(True) self.check_legend.setEnabled(True) self.line_edit_df_1.setEnabled(True) self.line_edit_df_2.setEnabled(True) # Añadimos los nombres de los dataframes a los LineEdits self.line_edit_df_1.setText(self.dataframes[0].name) self.line_edit_df_2.setText(self.dataframes[1].name) # Obtenemos los elementos del Layout que nos interesan # para generar los dos tipos de mapas (moviendo los elementos) self.dataframe1_scalebar = mapping.ListLayoutElements( self.mxd, '', 'data-frame-1-scale-bar')[0] self.dataframe1_scaletext = mapping.ListLayoutElements( self.mxd, '', 'data-frame-1-scale-text')[0] self.dataframe2_scalebar = mapping.ListLayoutElements( self.mxd, '', 'data-frame-2-scale-bar')[0] self.dataframe2_scaletext = mapping.ListLayoutElements( self.mxd, '', 'data-frame-2-scale-text')[0] self.legend_title = mapping.ListLayoutElements(self.mxd, '', 'legend-title')[0] self.legend_df1 = mapping.ListLayoutElements(self.mxd, '', 'legend-df-1')[0] self.legend_df2 = mapping.ListLayoutElements(self.mxd, '', 'legend-df-2')[0] self.map_title = mapping.ListLayoutElements(self.mxd, '', 'title')[0] self.dataframe1 = mapping.ListLayoutElements(self.mxd, '', 'data-frame-1')[0] self.dataframe2 = mapping.ListLayoutElements(self.mxd, '', 'data-frame-2')[0]
def plot_with_arcpy(init_time, replace_workspace_dir,origin_workspace_dir, images_dir, mxd_path, resolution=100): mxd = mp.MapDocument(mxd_path) # 修改预报时效 txts = mp.ListLayoutElements(mxd, "TEXT_ELEMENT") init_time_datetime = datetime.datetime.strptime(init_time, '%y%m%d%H') for valid_h, i in zip(range(0, 132, 12), range(23, 12, -1)): beg = (init_time_datetime + datetime.timedelta(hours=valid_h)).strftime('%d%H') end = (init_time_datetime + datetime.timedelta(hours=valid_h + 12)).strftime('%d%H') txts[i].text = beg + '-' + end # 替换数据源 mxd.replaceWorkspaces(origin_workspace_dir, "RASTER_WORKSPACE", replace_workspace_dir, "RASTER_WORKSPACE", False) # 处理缺失数据 broken_lyrs = mp.ListBrokenDataSources(mxd) for broken_lyr in broken_lyrs: # 让缺失数据图层及与其同在一个dataframe里其他的图层不显示 broken_df = mp.ListDataFrames(mxd, broken_lyr.name) if len(broken_dfs) > 0: lyrs_in_broken_df = mp.ListLayers(mxd, "", broken_df[0]) for lyr in lyrs_in_broken_df: lyr.visible = False #mxd.save() 不要保存 mp.ExportToJPEG(mxd, os.path.join(images_dir, init_time), resolution=resolution)
def populate_cancelled_taxlot_table(mxd, taxlots): """ Fill in the cancelled taxlot table in the page. Return the number of cancelled taxlots. """ #aprint("Populating cancelled taxlot table") # Count the can* columns in this MXD and empty them out. ncols = 0 cols = [] for elm in MAP.ListLayoutElements(mxd, "TEXT_ELEMENT", "can*"): if re.search('^can\d+$', elm.name): cols.append(elm) ncols += 1 elm.text = " " # This element has some text in it (event just a single space) so ArcMap does not "lose" it. if len(taxlots): # Sort out the data into as a list of columns max_y, columns = make_table(taxlots, ncols) # Adjust the font size of the table according to the number of rows fontsize = 10 if max_y > ORMAP.MaxCancelledRows: fontsize = 8 x = 0 for column in columns: cols[x].text = column cols[x].fontSize = fontsize x += 1 return
def update_cancelled(mxd, orm, x,y): global can_x, can_y can_elm = None try: can_elm = MAP.ListLayoutElements(mxd, "GRAPHIC_ELEMENT", "can*")[0] except IndexError: aprint("Could not find a cancelled taxlots group element. Skipping.") return # if on_page(can_elm,mxd): # can_x = can_elm.elementPositionX # can_y = can_elm.elementPositionY # elif can_x == 0 and can_y == 0: # aprint("The cancelled taxlots element \"%s\" is not on the map so it will never print." % can_elm.name) cancelled_taxlots = can.get_list(orm.dotted) aprint("Cancelled taxlots: %d" % len(cancelled_taxlots)) if len(cancelled_taxlots) == 0: # Move the cancelled taxlot table off the layout can_elm.elementPositionX = mxd.pageSize.width + 3 can_elm.elementPositionY = y else: can_elm.elementPositionX = x can_elm.elementPositionY = y populate_cancelled_taxlot_table(mxd, cancelled_taxlots) return
def make_scalebar_dict(mxd): sb = {} # make a list of all the scalebar elements in the map. for elem in MAP.ListLayoutElements(mxd, "MAPSURROUND_ELEMENT"): name = elem.name.lower() if name.find("scalebar") >= 0: sb[name] = elem return sb
def draw_graphic_maps(mxd, graphic_list): check_logo, check_date, check_legend, check_scale = graphic_list graphic_list_map = map.ListLayoutElements(mxd) for graphic in graphic_list_map: #Draw logo draw_graphic(graphic, 'logo_map', check_logo) #function created before #Draw Date draw_graphic(graphic, 'date_map', check_date) draw_graphic(graphic, 'hour_map', check_date) #Draw Legend draw_graphic(graphic, 'legend_map', check_legend)
def update_page_elements(mxd, df, orm): #aprint("Setting up page layout") select_scalebar(mxd, df.scale) try: elm = MAP.ListLayoutElements(mxd, "TEXT_ELEMENT", "PlotDate")[0] now = datetime.now() elm.text = "PLOT DATE: %2d/%02d/%4d" % (now.month, now.day, now.year) except IndexError: aprint("Could not find a PlotDate text element. Skipping.") return
def show_dataframes(mxd): # Use the list of data frames so report order will be correct. l_df = MAP.ListDataFrames(mxd) print(" DATA FRAMES:") for df in l_df: elm = MAP.ListLayoutElements(mxd, wildcard=df.name)[0] print(" Dataframe: " + elm.name) print(" X Position: " + str(elm.elementPositionX)) print(" Y Position: " + str(elm.elementPositionY)) print(" Height: " + str(elm.elementHeight)) print(" Width: " + str(elm.elementWidth)) print() show_layers(mxd, df)
def show_layout_element(mxd, element_name): l_elm = MAP.ListLayoutElements(mxd, element_name) if len(l_elm) > 0: print(" %s:" % element_name.replace('_', ' ')) # Sorted by "name" property for elm in sorted(l_elm, key=lambda x: x.name): print("\t Name: ", elm.name) if elm.type == "LEGEND_ELEMENT" or elm.type == "MAPSURROUND_ELEMENT": print("\t Parent data frame: ", elm.parentDataFrameName) if elm.type == "LEGEND_ELEMENT": print("\t Title: ", elm.title) if elm.type == "PICTURE_ELEMENT": print("\t Source image: ", elm.sourceImage) if elm.type == "TEXT_ELEMENT": # Todo - fix indent on multiline? print("\t Text string: ", elm.text) print("\t Angle: ", elm.angle) print("\t X Position: ", elm.elementPositionX) print("\t Y Position: ", elm.elementPositionY) print("\t Height: ", elm.elementHeight) print("\t Width: ", elm.elementWidth) print() print()
def zoomExtractMXD(parcel): #Variables mxd = MAP.MapDocument(mxdC) df = MAP.ListDataFrames(mxd)[0] parcelLyr = MAP.ListLayers(mxd, "Parcels", df)[0] jpg = os.path.join(outJPG, "%s") % (parcel) #Update Layers whereClause = "ACCOUNT ='%s'" % parcel arcpy.SelectLayerByAttribute_management(parcelLyr, "NEW_SELECTION", whereClause) #Make sure Account Exists getCount = arcpy.GetCount_management(parcelLyr) theCount = int(getCount.getOutput(0)) if theCount >= 1: df.extent = parcelLyr.getSelectedExtent(True) df.scale *= 1.1 #Update Text updatetext1 = MAP.ListLayoutElements(mxd, "TEXT_ELEMENT", "ACCOUNT")[0] updatetext1.text = parcel #Export to JPG MAP.ExportToJPEG(mxd, jpg) #Release MXD del mxd else: noAcctLog()
pass elif "Davao City" in mapdoc: mdoc_name = os.path.basename(mapdoc).split('.')[0] print '%d. %s' % (count, mdoc_name) mxd = mp.MapDocument(mapdoc) # save a backup of the mxd backup_mxd = os.path.join(backup_dir, mdoc_name + '.mxd') print "Saving as %s" % backup_mxd shutil.copy(mapdoc, backup_mxd) # update position of legend element #main_df = mp.ListDataFrames(mxd)[1] #main_lyrs = mp.ListLayers(mxd, "", main_df) leg_elm = mp.ListLayoutElements(mxd, "LEGEND_ELEMENT", "Legend")[0] leg_elm.elementPositionX = 8.8 leg_elm.elementPositionY = 5.7 - leg_elm.elementHeight #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=96) print '\n' del mxd
df.extent = BuildingLayer.getExtent() BuildingLayer.name = "Open Street Map buildings" RMSHDFishnetLayer.name = "RMSHD" OfficialFishnetLayer.name = "Official" ##search cityname - search cursor# SC = arcpy.SearchCursor(CityLayer, fields="CRESTA_DES") for row in SC: name = row.getValue("CRESTA_DES") del row, SC ########change the layout elements ######## #title for elm in (map.ListLayoutElements(mxd)): if elm.name == "Title": elm.text = str( "FLOODED BUILDINGS IN ") + name + ( " IN ") + cityTitle elm.elementPositionX = 0.1 elm.elementPositionY = 7.7656 if elm.name == "Subtitle": elm.text = str("Model provided by " + floodmodel) elm.elementPositionX = 0.22 elm.elementPositionY = 7.3252 if elm.name == "returnperiod": elm.text = str("Return period: " + returnperiod) elm.elementPositionX = 0.22
sTownship) + str(sTP) + str(sTownDir) + ". R." + str(sRange) + str( sRP) + str(sRangeDir) + ". W.M." if str(sSection) == "": sLongMapTitle = "T." + str(sTP) + str(sTownship) + str( sTownDir) + ". R." + str(sRange) + str(sRangeDir) + ". W.M." #MODIFY TITLE FOR NON-STANDARD MAPS if sMapType == "S": sLongMapTitle = "SUPPLEMENTAL MAP NO. " + str(sMN) + "\n" + sLongMapTitle if sMapType == "D": sLongMapTitle = "DETAIL MAP NO. " + str(sMN) + "\n" + sLongMapTitle if sMapType == "T": sLongMapTitle = "SHEET NO. " + str(sMN) + "\n" + sLongMapTitle #REPOSITION AND MODIFY PAGE ELEMENTS for elm in MAP.ListLayoutElements(MXD): #TEXT ELEMENTS if elm.name == "MapNumber": elm.text = MapNumber if elm.name == "MainMapTitle": elm.text = sLongMapTitle elm.elementPositionX = TitleX elm.elementPositionY = TitleY if elm.name == "CountyName": elm.text = PageConfig.CountyName elm.elementPositionX = TitleX elm.elementPositionY = TitleY - CountyNameDist if elm.name == "MainMapScale": elm.text = sMapScale elm.elementPositionX = TitleX elm.elementPositionY = TitleY - MapScaleDist
def delete_clone_elements(mxd): for elm in mapping.ListLayoutElements(mxd, wildcard="*_clone*"): elm.delete()
else: sys.exit( "Unable to find PageLayoutTable table. Please check your TOC and config file." ) #DETERMINE WHETHER TO INSERT OR UPDATE PAGELAYOUT ROW. if pageLayoutRow == None: theCursor = arcpy.InsertCursor(pageLayoutTable.name) theRow = theCursor.newRow() else: theCursor = arcpy.UpdateCursor(pageLayoutTable.name, "MapNumber = '" + MapNumber + "'") theRow = theCursor.next() #LOOP THROUGH THE PAGE ELEMENTS AND STORE THE VALUES IF POSSIBLE for elm in MAP.ListLayoutElements(MXD): theRow.MapNumber = MapNumber if len(arcpy.ListFields(pageLayoutTable.name, "MapAngle")) > 0: theRow.MapAngle = mainDF.rotation if elm.name == "MainDF": if len(arcpy.ListFields(pageLayoutTable.name, "DataFrameMinX")) > 0: theRow.DataFrameMinX = elm.elementPositionX if len(arcpy.ListFields(pageLayoutTable.name, "DataFrameMinY")) > 0: theRow.DataFrameMinY = elm.elementPositionY if len(arcpy.ListFields(pageLayoutTable.name, "DataFrameMaxX")) > 0: theRow.DataFrameMaxX = elm.elementPositionX + elm.elementWidth if len(arcpy.ListFields(pageLayoutTable.name, "DataFrameMaxY")) > 0: theRow.DataFrameMaxY = elm.elementPositionY + elm.elementHeight
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 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]
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())
def mappingProcess(datetime, province, target_area, density_class=None, day_class=10, out_path=None, out_type= "png"): # todo.控制densityClass和dayClass最多为14 cwd = os.getcwd() infeature = ''.join([cwd, u"/data/LightningBulletin.gdb/", target_area]) mxd_density_path = ''.join([cwd, u"/data/LightningBulletin.gdb/", target_area, u"闪电密度空间分布模板.mxd"]) mxd_day_path = ''.join([cwd, u"/data/LightningBulletin.gdb/", target_area, u"地闪雷暴日空间分布模板.mxd"]) workspace = ''.join([cwd, u"/temp/", province, '/', datetime, '/', target_area, '.gdb']) arcpy.env.workspace = workspace arcpy.env.overwriteOutput = True # *****处理地闪密度地图文档******* mxd = mapping.MapDocument(mxd_density_path) mask_lyr = mapping.ListLayers(mxd)[2] target_lyr = mapping.ListLayers(mxd)[3] mask_lyr.replaceDataSource(workspace, "FILEGDB_WORKSPACE", "densityMask") target_lyr.replaceDataSource(workspace, "FILEGDB_WORKSPACE", "lightningDensity") # 修改图例 # 计算数据分割值和不显示值 extract = ExtractByMask("lightningDensity", infeature) raster = Raster("lightningDensity") class_break_values, density_class = densityLegendLabel(extract.minimum / 100, extract.maximum / 100, density_class) excluded_values = ''.join([str(round(raster.minimum - 0.5, 2)), "-", str(round(extract.minimum - 0.5, 2)), ";", str(round(extract.maximum + 0.5, 2)), "-", str(round(raster.maximum + 0.5, 2))]) sym = target_lyr.symbology sym.excludedValues = excluded_values sym.classBreakValues = [x * 100 for x in class_break_values] # 更改标题和图例 layout_items = mapping.ListLayoutElements(mxd, "TEXT_ELEMENT") layout_items[-1].text = ''.join([datetime, target_area, u"闪电密度空间分布"]) # title标题 layout_items[-2].text = ''.join([target_area, u"气象局制"]) # 底注 density_class = class_break_values.__len__() - 1 class_break_values = [str(x) for x in class_break_values] # TODO 将position参数放到设置文件里,或者自动处理 position = {u"绍兴市": (1.0436, 1.6639, 0.9859272727272728), u"嵊州市": (1.1138, 1.2614, 0.9869090909090698), u"上虞区": (1.1372, 1.1617, 0.9862375000000156), u"诸暨市": (1.1138, 1.2614, 0.9869090909090698), u"柯桥区": (1.1372, 1.1617, 0.9862375000000156), u"新昌县": (1.1138, 1.2614, 0.9869090909090698), u"新乡市": (1.0436, 1.6639, 0.9859272727272728)} Y, Xstart, gap = position[target_area] for i in xrange(density_class + 1): layout_items[i].text = class_break_values[i] layout_items[i].elementPositionY = Y layout_items[i].elementPositionX = Xstart + gap * i for i in xrange(density_class + 1, 15): # 最多14类,15个标签 layout_items[i].elementPositionX = -20 mxd.save() if not out_path: out_path = workspace out_name = os.path.join(out_path, ''.join([datetime, target_area, u"闪电密度空间分布"])) out_type = out_type.lower() if out_type in ["jpg", 'gpeg']: mapping.ExportToJPEG(mxd, out_name, resolution=200) elif out_type == "png": mapping.ExportToPNG(mxd, out_name, resolution=200) elif out_type == "pdf": mapping.ExportToPDF(mxd, out_name) elif out_type == "bmp": mapping.ExportToBMP(mxd, out_name, resolution=200) else: mapping.ExportToTIFF(mxd, out_name, resolution=200) # *****处理雷暴日地图文档******* mxd = mapping.MapDocument(mxd_day_path) mask_lyr = mapping.ListLayers(mxd)[2] target_lyr = mapping.ListLayers(mxd)[3] mask_lyr.replaceDataSource(workspace, "FILEGDB_WORKSPACE", "dayMask") target_lyr.replaceDataSource(workspace, "FILEGDB_WORKSPACE", "lightningDay") # 修改图例 # 计算数据分割值和不显示值 extract = ExtractByMask("lightningDay", infeature) raster = Raster("lightningDay") start = floor(extract.minimum) end = ceil(extract.maximum) class_break_values, day_class = dayLegendLabel(start, end, day_class) excluded_values = ''.join([str(round(raster.minimum - 0.5, 2)), "-", str(round(extract.minimum - 0.5, 2)), ";", str(round(extract.maximum + 0.5, 2)), "-", str(round(raster.maximum + 0.5, 2))]) sym = target_lyr.symbology sym.excludedValues = excluded_values sym.classBreakValues = class_break_values # 更改标题和图例 layout_items = mapping.ListLayoutElements(mxd, "TEXT_ELEMENT") layout_items[-1].text = ''.join([datetime, target_area, u"地闪雷暴日空间分布"]) layout_items[-2].text = ''.join([target_area, u"气象局制"]) # 底注 Y, Xstart, gap = position[target_area] for i in xrange(day_class + 1): layout_items[i].text = class_break_values[i] layout_items[i].elementPositionY = Y layout_items[i].elementPositionX = Xstart + gap * i for i in xrange(day_class + 1, 15): # 最多14类,15个标签 layout_items[i].elementPositionX = -20 mxd.save() out_name = os.path.join(out_path, ''.join([datetime, target_area, u"地闪雷暴日空间分布"])) out_type = out_type.lower() if out_type in ["jpg", 'gpeg']: mapping.ExportToJPEG(mxd, out_name, resolution=200) elif out_type == "png": mapping.ExportToPNG(mxd, out_name, resolution=200) elif out_type == "pdf": mapping.ExportToPDF(mxd, out_name) elif out_type == "bmp": mapping.ExportToBMP(mxd, out_name, resolution=200) else: mapping.ExportToTIFF(mxd, out_name, resolution=200)
# 实验内容 # 1、 创建布局元素的列表; # 2、 为布局元素指定唯一名称; # 3、 限制返回的布局元素; # 4、 更新布局元素的属性; # 5、 导出地图为PDF文件 # 6、 导出地图为图像文件; # 7、 导出报表。 # 1 创建布局元素的列表 import arcpy.mapping as mapping mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") for el in mapping.ListLayoutElements(mxd): if el.name != "": print(el.name) # 3 限制返回的布局元素 import arcpy.mapping as mapping mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") for el in mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "*Crime*"): print(el.name) # 4 更新布局元素的属性 import arcpy.mapping as mapping mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") elLeg = mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "*Crime*")[0] elLeg.title = "Crime by School District" for item in elLeg.listLegendItemLayers():
#numpyArray to Raster conversion sel_dem = arcpy.NumPyArrayToRaster(mi_array, llc, cel_x, cel_y, no_data) #Save the result sel_dem.save( r'C:\asignaturas\sig1\2013-2014\cuatrimestreA\datos\sextante\sel_dem') #------------------------------------------------------------------------------- # ACCESS TEMPLATE ELEMENTS #------------------------------------------------------------------------------- #importing modules import arcpy import arcpy.mapping as map mxd = map.MapDocument(r'E:\asignaturas\layout.mxd') #listing all graphics elements within a layout for graphic in map.ListLayoutElements(mxd): #get the graphic element type print(graphic.type) #------------------------------------------------------------------------------- # ACCESS TEMPLATE TEXT #------------------------------------------------------------------------------- #importing modules import arcpy import arcpy.mapping as map mxd = map.MapDocument(r'I:\asignaturas\layout.mxd') #filtering all graphic elements by type for graphic in map.ListLayoutElements(mxd, 'TEXT_ELEMENT'): #get a graphic object using its name if graphic.name == 'text_name':
def update_locator_maps(mxd, orm): """ Update the locator maps to emphasize the area of interest. mxd = map document orm = ormap object, used in query definitions You can either create a mask or a highlighter based on queries in the configuration. Set up query definitions in each dataframe to control this. Returns the (x,y) location for the next stacked layout element. """ global sections_x, sections_y, qsections_x, qsections_y # We're trying a stacked layout here. The county-wide locator will be at the top, # and successive features will be below at suitable spacings. x = y = 0 for dfname,layers,extlayername,scale,fcount in [ (ORMAP.LocatorDF, ORMAP.LocatorLayers, ORMAP.LocatorExtentLayer, ORMAP.LocatorScale, ORMAP.LocatorFeatureCount), (ORMAP.SectionDF, ORMAP.SectionLayers, ORMAP.SectionExtentLayer, ORMAP.SectionScale, ORMAP.SectionFeatureCount), (ORMAP.QSectionDF, ORMAP.QSectionLayers, ORMAP.QSectionExtentLayer, ORMAP.QSectionScale, ORMAP.QSectionFeatureCount), ]: df = GetDataframe(mxd, dfname) # Set query definitions for layername, qd in layers: query = "" #aprint('qd = %s' % qd) if qd: try: query = eval(qd) except Exception as e: aprint("EVAL failed: query=\"%s\", %s" % (query, e)) SetDefinitionQuery(mxd, df, layername, query) # Set extent (pan and zoom as needed) # and possibly hide the locator map if extlayername: # Pan and zoom are optional in locator maps. ext_layer = GetLayer(mxd, df, extlayername) df.extent = ext_layer.getExtent() # if a fixed scale is specified in config, use it if scale: df.scale = scale # Now's our chance to hide (or show) locator maps!! visibility = True try: fc_layer = GetLayer(mxd,df,fcount) c = int(arcpy.GetCount_management(fc_layer).getOutput(0)) if c == 0: visibility = False aprint("Nothing to see in layer \"%s\"." % extlayername) except Exception as e: aprint("Error in %s, %s" % (extlayername, e)) elm = None try: elm = MAP.ListLayoutElements(mxd, "DATAFRAME_ELEMENT", dfname)[0] except IndexError: pass if elm: # leftover from before stacking was implemented # if on_page(elm, mxd): # # this element is on the page so save its location for future use # locator_positions[elm.name] = (elm.elementPositionX, elm.elementPositionY) # x=y=0 # try: # x = locator_positions[elm.name][0] # y = locator_positions[elm.name][1] # except: # aprint("Can't figure out where to put \"%s\"" % elm.name) if x <> 0 and y <> 0: # LocatorDF won't get moved because it's always visible elm.elementPositionX = x elm.elementPositionY = y if not visibility: elm.elementPositionX = mxd.pageSize.width + 2 elm.elementPositionY = y if on_page(elm, mxd): # Set position for the next element below this one x = elm.elementPositionX y = elm.elementPositionY - (elm.elementHeight + .15) return (x,y)
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
arcpy.AddMessage("Exporting to " + outputPath + "\\" + mapNumber + ".tif") arcpy.mapping.ExportToTIFF(MXD, outputPath + "\\" + mapNumber + ".tif", "PAGE_LAYOUT", resolution=res, tiff_compression=tifCompression) else: arcpy.AddMessage( "Unrecognized Print format. Unable to print map.") if printCurrent == "true": #-- Retrieve the mapnumber by looking at the mapnumber text in the upper right of layout if len(MAP.ListLayoutElements(MXD, "TEXT_ELEMENT", "MapNumber")) > 0: theMapNumberElm = MAP.ListLayoutElements(MXD, "TEXT_ELEMENT", "MapNumber")[0] theMapNumber = theMapNumberElm.text else: theMapNumber = "ORMAP_Map" printMap(theMapNumber) else: if printFromFile != "": text_file = open(printFromFile, "r") mapNumberList = text_file.readlines() for thisMap in mapNumberList:
#------------------------------------------------------------------------------- # GRAPHS #------------------------------------------------------------------------------- import arcpy import arcpy.mapping as map import arcgisscripting path = r"C:\Users\laboratorios\ELVLC\session6\session6.mxd" mxd = map.MapDocument(path) graphic_list = map.ListLayoutElements(mxd, "TEXT_ELEMENT") df = map.ListDataFrames(mxd)[0] layer = map.ListLayers(mxd, "", df)[0] layer_muni = map.ListLayers(mxd, "", df)[1] cur = arcpy.SearchCursor(layer) row = cur.next() while row: name = row.getValue("NOMBRE") code = row.getValue("PROVI") area = row.getValue("AREA") / 1000000 perimeter = row.getValue("PERIMETER") / 1000 name = row.getValue("NOMBRE") query = '"NOMBRE" = ' + "'" + name + "'" arcpy.SelectLayerByAttribute_management(layer, "NEW_SELECTION", query) df.zoomToSelectedFeatures() graphic_list = map.ListLayoutElements(mxd, "TEXT_ELEMENT") for graphic in graphic_list: if graphic.name == "txt_name": graphic.text == name if graphic.name == "txt_vode": graphic.text = str(cod) if graphic.name == "txt_area":
import arcpy.mapping as mapping mxd = mapping.MapDocument("CURRENT") for el in mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "*fil*"): print el.name
## 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") del mxd
continue TiffLyr.replaceDataSource(qinshi_raster_dir, "RASTER_WORKSPACE", newTiffName) # newShpName不带后缀 #bufferLyr.replaceDataSource(newShpPath, "SHAPEFILE_WORKSPACE", newBufferName) mxd.saveACopy(out_fmxd) # 将替换后的mxd保存至outfPath # ========================= 开始设置输出元素 ====================== # 先读取上面保存的mxd初始化为mxd2 mxd_ = mapping.MapDocument(mxds_dir + os.sep + fname + ".mxd") df_mxd = mapping.ListDataFrames(mxd_)[0] layers = arcpy.mapping.ListLayers(mxd_, "", df_mxd) for lyr in layers: if lyr.name == 'QD.tif': TiffLyr = lyr # 设置比例尺 df_mxd.extent = TiffLyr.getExtent() # 缩放至图层 df_mxd.extent = TiffLyr.getExtent() # 缩放至图层 txtElm = mapping.ListLayoutElements(mxd_, "DATAFRAME_ELEMENT")[0] df_mxd.scale = int(txtElm.scale * 0.0001) * 10000 # df.scale = 1875523 #1:1875523 # 设置title # mxd2.title = newCityName + u"土壤侵蚀分布图" arcpy.RefreshActiveView() # 刷新地图和布局窗口 arcpy.RefreshTOC() # 刷新内容列表 mxd_.save() # 将替换后的mxd保存至outfPath out_tiff = dir_mxd + os.sep + 'OutFiles\\TIFS' + os.sep + fname + u'_土壤侵蚀.tif' mapping.ExportToTIFF(mxd_, out_tiff=out_tiff, resolution=300) # arcpy.mapping.ExportToPNG(mxd2, outDir + os.sep + fname +u'侵蚀.png') print(fname + "output OK")
import arcpy.mapping as mapping mxd = mapping.MapDocument("CURRENT") for el in mapping.ListLayoutElements(mxd): if el.name != '': print el.name