def tryit(): mxd = arcpy.mapping.MapDocument( "C:\\Users\\Bougie\\Desktop\\Gibbs\\documents\\temp\\try2.mxd") # lyr_ref = arcpy.mapping.ListLayers(mxd, "cdl30_2012")[0] lyr = arcpy.mapping.ListLayers(mxd, "tile_mtr")[0] # arcpy.SelectLayerByAttribute_management(lyr_ref, "NEW_SELECTION") classList = [22, 12, 23, 61, 87] # rows = arcpy.da.SearchCursor(lyr_ref, ["Class_Names"]) # for row in rows: # classList.append(row[0]) # print lyr.symbologyType == "UNIQUE_VALUES" # if lyr.symbologyType == "UNIQUE_VALUES": # print 'hi' lyr.symbology.classLabels = classList # lyr.symbology.showOtherValues = False # lyr.symbology.addAllValues() arcpy.RefreshActiveView() arcpy.RefreshTOC() del mxd
def remove_multiple_layers(in_data): """Given a list of the features (feature classes and tables), remove them from the map. This must be done before the delete_features function can be called, so that there will be no schema lock issues.""" arcpy.AddMessage("Removing") mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "*")[0] for lyr in arcpy.mapping.ListLayers(mxd, "", df): for fc in in_data: if lyr.name == "DDPINDEX" or lyr.name == fc[15:]: arcpy.mapping.RemoveLayer(df, lyr) for tab in arcpy.mapping.ListTableViews(mxd, "", df): for ele in in_data: if tab.name == ele[15:]: arcpy.mapping.RemoveTableView(df, tab) arcpy.RefreshActiveView() arcpy.RefreshTOC() del df arcpy.AddMessage("Done Removing")
def symbolize_vectors(vectors_to_symbolize, lyr_file_param=""): mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd)[0] # Loop through every layer in the mxd document for lyr in arcpy.mapping.ListLayers(mxd, "", df): # Check if it is in the list of vector layers: if lyr.name in vectors_to_symbolize: # Get the chosen Lyr template used if len(lyr_file_param) > 0: lyr_file = arcpy.mapping.Layer(base_path + "\\Lyr\\" + lyr_file_param + ".lyr") else: lyr_file = arcpy.mapping.Layer(base_path + "\\Lyr\\" + lyr.name + ".lyr") print("Symbolize:" + lyr.name) # Apply the Lyr template to it arcpy.mapping.UpdateLayer(df, lyr, lyr_file, True) # Refresh the display of the mxd arcpy.RefreshActiveView() arcpy.RefreshTOC()
def selectTipoPeligro(self, listTipo): df = arcpy.mapping.ListDataFrames(self.mxd, "Leyenda")[0] ptLeyenda = arcpy.mapping.ListLayers(self.mxd, "GPT_HM_Leyenda")[0] arcpy.DeleteRows_management(ptLeyenda) xini = 0 yini = 0 rowx = 0 rowy = 0 cursor = arcpy.da.InsertCursor(ptLeyenda, ["SHAPE@X", "SHAPE@Y", "TIPO"]) for i in range(len(listTipo)): cursor.insertRow([xini + rowx, yini + rowy, listTipo[i]]) if len(listTipo) > 1: rowy = rowy - 0.004 if i == 7: rowy = 0 rowx = 0.032 del cursor arcpy.RefreshActiveView() self.updateScale(df, ptLeyenda)
def execute(self, parameters, messages): rastername = parameters[0].valueAsText trainpts = parameters[1].valueAsText unitcell = parameters[2].value Temp_Symbology = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..\\raster_classified.lyr') desc = arcpy.Describe(rastername) arcpy.AddMessage(Temp_Symbology) arcpy.AddMessage("=" * 20 + " starting symbolize " + "=" * 20) arcpy.AddMessage("%-20s %s" % ("Raster name: ", desc.file)) rastername = desc.file mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "")[0] lyr = arcpy.mapping.ListLayers(mxd, rastername, df)[0] prob = arcsdm.sdmvalues.getPriorProb(trainpts, unitcell, arcsdm.sdmvalues.getMapUnits()) arcpy.AddMessage("%-20s %s" % ("Probability: ", str(prob))) arcpy.AddMessage( "Applying raster symbology to classified values from lyr file... ") arcpy.ApplySymbologyFromLayer_management(lyr, Temp_Symbology) if lyr.symbologyType == "RASTER_CLASSIFIED": #lyr.symbology.classBreakValues = [1, 60, 118, 165, 255] arcpy.AddMessage("Setting values to prob priority values ... ") values = lyr.symbology.classBreakValues values[0] = 0 values[1] = prob #TODO: Does this need rounding? lyr.symbology.classBreakValues = values #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.reclassify() #lyr.symbology.excludedValues = '0' arcpy.RefreshActiveView() arcpy.RefreshTOC() del mxd, df, lyr
def add_outputs(self): self.output.delete_output("SvB_Saldo") gemeinde_werte = lib_einnahmen.get_values(["SvB_Saldo"], self.projectname) symbology = lib_einnahmen.get_symbology(gemeinde_werte, 1) self.output.add_layer(groupname="einnahmen", featureclass="Gemeindebilanzen", template_layer=symbology, template_folder="einnahmen", name="SvB-Saldo", disable_other=True, symbology={'valueField': "SvB_Saldo"}, label_replace={'Einw_Saldo': 'SvB_Saldo'}) diagram = Dia_Wanderung_SvB(projectname=self.par.name.value) self.output.add_diagram(diagram) arcpy.RefreshTOC() arcpy.RefreshActiveView()
def onClick(self): print "Execution du Extract by Mask..." # Set local variables inRaster = rasterPath inMaskData = mask_class # Execute ExtractByMask outExtractByMask = arcpy.sa.ExtractByMask(inRaster, inMaskData) arcpy.MakeRasterLayer_management(outExtractByMask, "extracted raster") # Dé-sélection des couches inutiles selectedLayers = ["maskRaster", "rasterLayer"] mxd = arcpy.mapping.MapDocument("current") df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] layers = arcpy.mapping.ListLayers(mxd, "*", df) for layer in layers: if layer.name in selectedLayers: layer.visible = False arcpy.RefreshTOC() arcpy.RefreshActiveView()
def DataRenderingOutput(mymxd): mymap = arcpy.mapping.MapDocument(mymxd) layers = arcpy.mapping.ListLayers(mymap) for layer in layers: layer.showLabels = True layer.labelClasses[0].expression = '[NAME]' arcpy.RefreshTOC() arcpy.RefreshActiveView() mypdf = arcpy.mapping.PDFDocumentCreate("e:/data/newpdf.pdf") lyr = arcpy.mapping.ListLayers(mymap)[4] df = arcpy.mapping.ListDataFrames(mymap)[0] rows = arcpy.SearchCursor(lyr) for row in rows: geo = row.shape # df.zoomToSelectedFeatures() df.panToExtent(geo.extent) outFile = "e://data//" + row.getValue("NAME") + ".pdf" outFile1 = outFile.replace('?', '') arcpy.mapping.ExportToPDF(mymap, outFile1) mypdf.appendPages(outFile1) mypdf.saveAndClose() mymap.save()
def commit_geometry(self, tablename, shape, element_id, additional_columns={}): """insert geometry with spec. id into given table """ netz_id = self.netz_ids[element_id] project=config.active_project table = folders.get_table(tablename, workspace='FGDB_Kosten.gdb', project=project) columns = (['id', "SHAPE@", 'IDNetzelement', 'IDNetz'] + additional_columns.keys()) cursor = arcpy.da.SearchCursor(table, ['id']) ids = [row[0] for row in cursor] id = 1 if not ids else max(ids) + 1 cursor = arcpy.da.InsertCursor( table, columns) try: cursor.insertRow([id, shape, element_id, netz_id] + additional_columns.values()) except Exception as e: print(e) finally: del(cursor) arcpy.RefreshActiveView()
def slope_analysis(slope_single): ## Find Suitable_Slope arcpy.AddMessage('-Calculating Appropriate Slope') Suitable_Slope = LessThan( 'Slope_DEM', slope_single ) ##This is the input that we want to be able to change/adjust # Part 3 # Buffer, Extract, by Mask, and Raster Calculator arcpy.AddMessage('Part 3: Buffer, Extract by Mask, and Raster Calculator') ## (Input Feature, Output Feature, Distance : Linear Unit, Side Type [0], ## End Type [0], Dissolve Type [0], Dissolve Fields [0]) arcpy.AddMessage('-buffer (' + str(Highways) + ') Tool Running') arcpy.Buffer_analysis(Highways, Highways_Buffer, '2 Kilometers', 'FULL', 'ROUND', 'ALL', '') #Delete Code Below #arcpy.AddMessage ('-buffer (' + str(Access_Roads) + ') Tool Running') #arcpy.Buffer_analysis(Highways, Access_Roads_Buffer, '0.1 Kilometers', 'FULL', 'ROUND', 'ALL', '') #arcpy.Erase_analysis(Highways_Buffer, Access_Roads_Buffer, Final_Buffer, '') ## Extract by Mask Highways with SuitableSlope ## (Input Raster, Feature Mask Data) arcpy.AddMessage('-Extract by Mask Tool Running') SuitableSlopebyRoads = ExtractByMask(Suitable_Slope, Highways_Buffer) ## Raster Calculator for SuitableSlopebyRoads and TowerDensityDEM arcpy.AddMessage('-Calculating Suitable Cell Tower Sites') Final_Suitability_Sites = SuitableSlopebyRoads * 'TowerDensityDEM' Final_Suitability_Sites.save('Final_Suitability_Sites1') #Add Final_Suitability_Sites to Map arcpy.AddMessage('-Add Final_Suitability_Sites to Map as a Layer') mxd = arcpy.mapping.MapDocument('CURRENT') df = arcpy.mapping.ListDataFrames(mxd, 'County Map')[0] arcpy.MakeRasterLayer_management('Final_Suitability_Sites1', 'Final_Suitability_Sites') newlayer = arcpy.mapping.Layer('Final_Suitability_Sites') arcpy.ApplySymbologyFromLayer_management(newlayer, raster_symbology) arcpy.mapping.AddLayer(df, newlayer, 'TOP') arcpy.RefreshActiveView() mxd.save arcpy.AddMessage('Final Suitability Sites Layer Added')
def getImpactMXD(fire_prefix, run_output, fire, extent, perim): """! Save impact map for given inputs @param fire_prefix prefix to use for file name @param run_output Folder simulation output was saved to @param fire Fire simulation was for @param extent Extent to use for map @param perim Perimeter to display on map @return Path used for saving output with given inputs @return MapDocument with opened output @return extent Extent that was applied to the map """ logging.debug("Called getImpactMXD()") sim_output = readSimOutput(run_output) map_output = getMapOutput(run_output) copyMXD = getImpactMXDName(fire_prefix, run_output, fire, extent, perim) shutil.copyfile(os.path.join(Settings.HOME_DIR, "mxds", "impact.mxd"), copyMXD) theMXD = arcpy.mapping.MapDocument(copyMXD) impact = Settings.RAMPART_MASK.format( 'high', findSuffix(findFuelRaster(sim_output))) setDataSource(theMXD, "*Potential Impact*", impact) txtAssumptions = ( "Potential Impact is based on staff assessment of impact on a 1 - 10 scale,\n" "representing the loss from the damage or disruption from various types of RA data\n" "burned with a 4000+ kW/m head fire intensity. Each cell is coloured based on the\n" "amount and type of RA within it. Potential Impact is the 'worst case'\n" "and the risk calculation on subsequent maps is a downscaling of this (e.g., burned\n" "with lower fire intensity and/or lower probability). Warning: use with caution and\n" "awareness of the assumptions and simplifications. Impact does not include indirect\n" "(e.g. smoke) or long-term effects. A hectare must burn in the model to show any risk;\n" "limitations of FireSTARR apply. RA may be missing from the GIS database, affecting\n" "results.") setCommon(theMXD, fire, txtAssumptions, " ", run_output, fire, perim, extent, impact) arcpy.RefreshActiveView() theMXD.save() return copyMXD, theMXD
def observacionesCroquis(mxd, empruta, idruta, idaer, conn=conn): cursor = conn.cursor() cursor.execute("SELECT COUNT(IDCCPP) AS CANT_CCPP, SUM(VIV_CCPP) AS VIV_EMP FROM SEGM_R_CCPPRUTA WHERE IDRUTA = '{}' AND IDAER = '{}'".format(idruta, idaer)) informacion = [[x[0], x[1]] for x in cursor] cursor.close() del cursor ConteoCCPP = informacion[0][0] viviendasccppruta = informacion[0][1] ElementoTexto16 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "CCPP_OBS")[0] ElementoTexto17 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "VIV_OBS")[0] ElementoTexto16.text = "01 CENTRO POBLADO." if ConteoCCPP == 1 else "{} CENTROS POBLADOS.".format( str(ConteoCCPP).zfill(3)) if empruta > 1: ElementoTexto17.text = 'LAS VIVIENDAS A TRABAJAR SERÁN ASIGNADAS EN CAMPO POR EL JEFE DE SECCIÓN.' elif empruta == 1 and ConteoCCPP == '1': ElementoTexto17.text = 'EL CUAL CONTIENE {} VIVIENDAS.'.format(viviendasccppruta) elif empruta == 1 and ConteoCCPP != '1': ElementoTexto17.text = 'QUE SUMAN {} VIVIENDAS.'.format(viviendasccppruta) arcpy.RefreshActiveView()
def informacionCabecera(lista, mxd): ElementoTexto1 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "CCDD")[0] ElementoTexto2 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "DEPARTAMENTO")[0] ElementoTexto3 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "CCPP")[0] ElementoTexto4 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "PROVINCIA")[0] ElementoTexto5 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "CCDI")[0] ElementoTexto6 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "DISTRITO")[0] ElementoTexto1.text = lista[0][0:2] ElementoTexto2.text = lista[1] ElementoTexto3.text = lista[0][2:4] ElementoTexto4.text = lista[2] ElementoTexto5.text = lista[0][4:6] ElementoTexto6.text = lista[3] arcpy.RefreshActiveView()
def add_multiple_layers_back(file_GDB_data, file_GDB_floorplans, in_data): """Given the location of the local file GDB and the features, add the feature class from the local file GDB back into the map.""" arcpy.AddMessage("Adding back") mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "*")[0] #Tables aren't considered layers so have to treat tables differently #Create a new layer #When the feature class is replicated into the file geodatabase, the prefix "foorplans.DBO." needs to be stripped out for fc in in_data: try: fc_layer = arcpy.mapping.Layer(file_GDB_data + "\\" + fc[15:]) except: fc_layer = arcpy.mapping.TableView(file_GDB_data + "\\" + fc[15:]) #Add the layer to the map at the bottom of the TOC in data frame 0 try: arcpy.mapping.AddLayer(df, fc_layer, "BOTTOM") except: arcpy.mapping.AddTableView(df, fc_layer) del fc_layer ddpindex_layer = arcpy.mapping.Layer(file_GDB_floorplans + "\DDPINDEX") arcpy.mapping.AddLayer(df, ddpindex_layer, "BOTTOM") for lyr in arcpy.mapping.ListLayers(mxd): if lyr.name == "DDPINDEX": lyr.visible = False #Refresh map arcpy.RefreshTOC() arcpy.RefreshActiveView() del df, ddpindex_layer arcpy.AddMessage("Done Adding back")
def update_page_layout(mxd, pagename): """Update the map document page layout using the given pagename.""" try: maindf = mxd.dataDrivenPages.dataFrame ddp_layer = mxd.dataDrivenPages.indexLayer except Exception as e: aprint(e) return page_id = mxd.dataDrivenPages.getPageIDFromName(pagename) mxd.dataDrivenPages.currentPageID = page_id orm = ormapnum() orm.expand(pagename) #aprint("%s -> %s -> %s" % (pagename, orm.dotted, orm.longmaptitle)) update_page_elements(mxd, maindf, orm) (x,y) = update_locator_maps(mxd, orm) update_cancelled(mxd, orm, x,y) arcpy.RefreshActiveView() return
def createMxd(modelpath, mxdpath, filename, jpgpath): mxd = arcpy.mapping.MapDocument(modelpath) if (os.path.exists(mxdpath)): mxd = arcpy.mapping.MapDocument(mxdpath) print("location as " + mxdpath) arcpy.AddWarning("该文件已经存在") else: mxd.saveACopy(mxdpath) print(mxdpath + " saveAs succefssful") if (os.path.exists(mxdpath)): mxd = arcpy.mapping.MapDocument(mxdpath) print("location in " + mxdpath) # 查找数据框 df = arcpy.mapping.ListDataFrames(mxd, "*")[0] # 增加底图 #symbologyLayer = "D:\\cs\\model\\lyr\\Rectangle_#1_常熟卫图_Level_16.tif.lyr" #"F:\\xinxiang\\fil\\20190817mydPM25.tif" shpLayer = arcpy.mapping.Layer(filename) arcpy.mapping.AddLayer(df, shpLayer, "TOP") df.extent = shpLayer.getExtent() arcpy.RefreshActiveView() arcpy.RefreshTOC() mxd.save() arcpy.mapping.ExportToJPEG(mxd, jpgpath, resolution=res)
def export_maps_each_feature(fc, mxd_file, unique_fieldname, output_png_dir): arcpy.RefreshActiveView() ## declared mxd as current (instead of mxd filepath) mxd = arcpy.mapping.MapDocument('CURRENT') ## or 'C://...map.mxd' ## got my mapdataframe form the mxd object map_df = arcpy.mapping.ListDataFrames(mxd, '*')[0] ## for boro_name in list_of_boronames: df = feature_class_to_dataframe(fc) field_values_list = df[unique_fieldname].unique() for field_value in field_values_list: ## selected features by attribute from layer - attribute being boroname arcpy.SelectLayerByAttribute_management( fc, "NEW_SELECTION", """ "{}" = '{}' """.format(unique_fieldname, field_value), ) ## zoom to selected feature map_df.zoomToSelectedFeatures() ## exported the png arcpy.SelectLayerByAttribute_management( fc, "CLEAR_SELECTION") ## just to get rid of outline arcpy.mapping.ExportToPNG( mxd, '{}_{}.png'.format(output_png_dir, field_value))
def onClick(self): sourceLayer = arcpy.mapping.Layer( r"P:\Projects\__ArcMap_Master_GDB_LYR\CIR.lyr") mxd = arcpy.mapping.MapDocument("Current") df = arcpy.mapping.ListDataFrames(mxd, "*")[0] text_file = open("C:/timer_tiles/tile_list.txt", "r") lines = text_file.readlines() text_file.close() for i in range(0, len(lines)): newlayer = arcpy.mapping.Layer(lines[i]) arcpy.mapping.UpdateLayer(df, newlayer, sourceLayer, symbology_only=True) arcpy.mapping.AddLayer(df, newlayer, "Bottom") del newlayer arcpy.RefreshActiveView() arcpy.RefreshTOC() del mxd, df
def resetpoint(): mxd = arcpy.mapping.MapDocument("CURRENT") lyr = arcpy.mapping.ListLayers( mxd, pythonaddins.GetSelectedTOCLayerOrDataFrame())[0] with arcpy.da.UpdateCursor(lyr, [ "count", decidefield, newx, newy, "SHAPE@X", "SHAPE@Y", "longitude", "latitude", movecount ]) as features: for feature in features: # set decision field and new x,y attribute fields to null feature[1] = None feature[2] = None feature[3] = None # set geometry attributes to X,Y coordinates based on attribute table feature[4] = feature[6] feature[5] = feature[7] # reset count of # of times feature has been moved to 0 feature[8] = "0" features.updateRow(feature) # thisid = int(feature[0]) # expression = 'count = ' + str(thisid) # exp2 = expression.replace("'", "") # arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", exp2) arcpy.RefreshActiveView()
def onClick(self): """Set layer definition query based on current config filter file.""" query_items = [] config_dict = self.read_config_xml(configure_filter.xml_path) for name, config in sorted(config_dict['config'].iteritems()): if name in self.reverse_subs: name = self.reverse_subs[name] query_string = "%s >= %s AND %s <= %s" % (name, config['USER_MIN'], name, config['USER_MAX']) if int(config['USER_NULL_FLAG']) == 1: query_string += " OR %s IS NULL" % name query_string = "(" + query_string + ")" query_items.append(query_string) query_string = " AND ".join(query_items) layer_name = config_dict['name'] layer = self.get_feature_layers(self.mxd, layer_name)[0] layer.definitionQuery = query_string arcpy.RefreshActiveView()
def run(self): markets_df = self.parent_tbx.markets_df # check which markets should be deleted, the other ones will be updated delete_df = markets_df.loc[markets_df['do_delete'] == True] update_df = markets_df.loc[markets_df['do_delete'] == False] # deletions if len(delete_df) > 0: arcpy.AddMessage(u'Lösche Märkte') for idx, market in delete_df.iterrows(): arcpy.AddMessage(u' - {}'.format(market['pretty'])) self.parent_tbx.delete_rows_in_table('Maerkte', where='id={}'.format( market['id'])) self.parent_tbx.delete_rows_in_table('Beziehungen_Maerkte_Zellen', where='id_markt={}'.format( market['id'])) # updates arcpy.AddMessage(u'Schreibe Änderungen in Datenbank...') self.parent_tbx.dataframe_to_table('Maerkte', update_df, ['id'], upsert=False) arcpy.RefreshActiveView()
def _show_layer(self, layer, redraw=True): """show the layer by adding it to the TOC of ArcGIS""" current_mxd = arcpy.mapping.MapDocument("CURRENT") current_dataframe = current_mxd.activeDataFrame self.set_backgroundgrouplayer(current_dataframe) if not redraw and self.layer_exists(layer.name): arcpy.RefreshActiveView() return self.remove_layer(layer.name) projektname = self.projectname group = self.module.get_label(layer.groupname) current_dataframe.geographicTransformations = [ 'DHDN_To_WGS_1984_5x', 'DHDN_To_ETRS_1989_5' ] # Layer-Gruppen hinuzfuegen, falls nicht vorhanden self.set_projectlayer(projektname) project_layer = self.get_projectlayer(projektname) # Template Layer laden template_layer = self.folders.get_layer(layer.template_layer, layer.template_folder) if not os.path.exists(template_layer): raise Exception( 'Layer-file {} does not exist!'.format(template_layer)) #arcpy.AddMessage(template_layer) source_layer = arcpy.mapping.Layer(template_layer) # Datasource des Layers auf die gewünschte FeatureClass setzen if layer.featureclass: featureclass = self.folders.get_table(layer.featureclass, workspace=layer.workspace) source_ws = source_layer.workspacePath target_ws = arcpy.Describe(featureclass).path #source_layer.findAndReplaceWorkspacePath(source_ws, target_ws) source_layer.replaceDataSource(dataset_name=layer.featureclass, workspace_path=target_ws) # Untergruppen hinzufügen if layer.in_project: self.set_grouplayer(group, project_layer, current_dataframe) #for l in self.get_layers(group)[0]: l.visible = True if layer.subgroup != "": self.set_subgrouplayer(group, layer.subgroup, project_layer, current_dataframe) # Neuen Layer hinzufuegen target_grouplayer = arcpy.mapping.ListLayers( project_layer, group, current_dataframe)[0] else: target_grouplayer = arcpy.mapping.ListLayers( current_mxd, group, current_dataframe)[0] # Layer zur Group oder Subgroup hinzufügen if not layer.subgroup: self.add_or_replace_layer(target_grouplayer, current_dataframe, source_layer) else: target_subgrouplayer = arcpy.mapping.ListLayers( target_grouplayer, layer.subgroup, current_dataframe)[0] self.add_or_replace_layer(target_subgrouplayer, current_dataframe, source_layer) # neuer Layer new_layer = arcpy.mapping.ListLayers(target_grouplayer, source_layer.name, current_dataframe)[0] # Auf Layer zentrieren if layer.zoom: if layer.zoom_extent is not None: ext = arcpy.Extent(*layer.zoom_extent) else: ext = new_layer.getExtent() current_dataframe.extent = ext if layer.disable_other == True: for lyr in arcpy.mapping.ListLayers(project_layer): lyr.visible = False if layer.symbology_classes is not None: num_symclasses, column = layer.symbology_classes self.update_layersymbology(new_layer, num_symclasses, column) new_layer.visible = layer.visible for lyr in arcpy.mapping.ListLayers(new_layer): lyr.visible = layer.visible new_layer.name = layer.name if layer.query: new_layer.definitionQuery = layer.query if layer.subgroup != "": target_subgrouplayer.visible = True # not all layers support symbology try: sym = new_layer.symbology for f, v in layer.symbology.iteritems(): setattr(sym, f, v) except Exception as e: pass #print(e) # same with labels try: for label_class in new_layer.labelClasses: exp = label_class.expression for l, v in layer.label_replace.iteritems(): exp = exp.replace(l, v) label_class.expression = exp except Exception as e: pass #print(e) target_grouplayer.visible = True if layer.in_project: project_layer.visible = True if layer.show_wms_legends: url = new_layer.serviceProperties['URL'] for l in new_layer: name = l.serviceProperties['Name'] legend_url = url + '&layer={}'.format(name) legend_url += '&sld_version=1.1.0&request=GetLegendGraphic&service=WMS&version=1.3.0&format=image/png' fn = name + '.png' fp = os.path.join(os.path.split(template_layer)[0], fn) arcpy.Delete_management(fp) title = l.serviceProperties['WMSTitle'].encode('utf-8') r = requests.get(legend_url, stream=True) if r.status_code == 200: with open(fp, 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) legend = Image(fp, title) self._show_image(legend) self.sort_layers() del (current_dataframe) del (new_layer) del (current_mxd)
def print_map(names_to_load1, output_text_ID, sp_code_st, resultsdir, overwrite_res): sp_code_st="0001" output_text_ID="test" names_to_load1=["current_envelope", "all_points"] #XXXXXXXXXXXXXXXXXXX sp_code=int(sp_code_st) sp_code=str(sp_code) nf=0 try: Sp_index=all_sp_codes.index(sp_code) except ValueError: nf=1 sp_name="Unkown" if nf==0: sp_name=New_sp_names[Sp_index] output_path = resultsdir+ "output_maps/"+ sp_code_st +"_"+ sp_name + "_" + output_text_ID + ".tif" if overwrite_res==0 and arcpy.Exists(output_path): print sp_code + " calculated already" else: current_envelope='%sCEs/CCE%s.tif' %(resultsdir,sp_code_st) all_points=r"%scorrected_CO_data4_merged_and_filtered.shp" %(CAO_data_dir) To_load0=[current_envelope, all_points] names_to_load0=["current_envelope", "all_points"] ref_layers0=["ref_lyr_protected_zones_map1.lyr", "ref_lyr_CEP.lyr"] # To_load00=[] ref_layers00=[] names_to_load00=[] for name in names_to_load1: jnk=names_to_load0.index(name) To_load00.append(To_load0[jnk]) ref_layers00.append(ref_layers0[jnk]) names_to_load00.append(name) To_load=[] ref_layers=[] names_to_load=[] for i in range(len(To_load00)): if arcpy.Exists(To_load00[i]): To_load.append(To_load00[i]) ref_layers.append(ref_layers00[i]) names_to_load.append(names_to_load00[i]) for df in arcpy.mapping.ListDataFrames(mxd): mxd.activeView = df.name for i in range(len(To_load)): fc=To_load[i] if fc[-4:]==".tif": fc_lyr=fc[:-4] +"_temp.lyr" fc_pluspath=fc fc_rl_temp=names_to_load[i] #fc[:-4]+"temp" sourceLayer0=ref_lyr_dir+ref_layers[i] arcpy.MakeRasterLayer_management(fc_pluspath, fc_rl_temp, "#", "", "#") arcpy.ApplySymbologyFromLayer_management(fc_rl_temp, sourceLayer0) if fc[-4:]==".shp": #import shp! arcpy.MakeFeatureLayer_management(fc, "CO_lyr") expr=""" "sp_name" = '%s' """ %(sp_name) arcpy.SelectLayerByAttribute_management ("CO_lyr", "NEW_SELECTION", expr) sp_CO_points_loc=resultsdir+sp_code_st+"_sp_CO_points.shp" arcpy.CopyFeatures_management("CO_lyr", sp_CO_points_loc) #fc_lyr=fc[:-4] +"_temp.lyr" #fc_pluspath=fc #fc_rl_temp=names_to_load[i] #fc[:-4]+"temp" sourceLayer0=ref_lyr_dir+ref_layers[i] #arcpy.MakeFeatureLayer_management (fc_pluspath, fc_rl_temp, "#", "", "#") #arcpy.MakeFeatureLayer_management (sp_code_st+"_sp_CO_points", fc_rl_temp, "#", "", "#") arcpy.ApplySymbologyFromLayer_management(sp_code_st+"_sp_CO_points", sourceLayer0) pass arcpy.RefreshActiveView() arcpy.RefreshTOC() if len(To_load)>0: if print_map_output==1: arcpy.mapping.ExportToTIFF(mxd, output_path) for df in arcpy.mapping.ListDataFrames(mxd): mxd.activeView = df.name for i in range(len(To_load)): fc_rl_temp=names_to_load[i] #fc[:-4]+"temp" try: del_layer(fc_rl_temp) except: pass try: arcpy.Delete_management(fc_rl_temp) except: pass jnks=arcpy.mapping.ListBrokenDataSources(df) for jnk in jnks: arcpy.mapping.RemoveLayer(df, jnk) arcpy.RefreshActiveView() arcpy.RefreshTOC() #remove these map layers!! return #sp_code_st = sp_codes[0] for sp_code_st in sp_codes: t0 = time.time() t00=t0 names_to_load1=["current_envelope", "Current occurence records"] #, "Points beyond response zone" output_text_ID = "points_and_current_CE" print_map(names_to_load1, output_text_ID, sp_code_st, resultsdir, overwrite_res) t1 = time.time() print 'It took %i seconds to rrun code for species %s' %(int(t1-t00), sp_code_st)
def execute(self, parameters, messages): """The source code of the tool.""" # local variables and env arcpy.CreateFileGDB_management("E:/gina/poker/gdb", parameters[0].valueAsText) arcpy.env.workspace = "E:/gina/poker/gdb/" + parameters[ 0].valueAsText + ".gdb" arcpy.env.overwriteOutput = True adnr_lo_shp = "E:/gina/poker/shp/wip/land_ownership_data/adnr_gls_dls_merge_20170823_v1.shp" pfrr_popn_places = "E:/gina/poker/shp/wip/popn_places_data/pokerflat_popn_places_gcs_wgs84_to_akalbers_2.shp" afs_known_sites = "E:/gina/poker/shp/asf_data/asf_known_sites_20180629_3338.shp" pipTable = "E:/gina/poker/dbf/predicted_impact_xy.dbf" pip_point_shp = "E:/gina/poker/pip/pip_point.shp" pip_point_3338 = "E:/gina/poker/pip/pip_point_3338.shp" pip_buffer_shp = "E:/gina/poker/pip/pip_buffer.shp" pip_range_rings_shp = "E:/gina/poker/pip/pip_range_rings.shp" pip_lo_in_buffer_shp = "E:/gina/poker/pip/pip_lo_in_buffer.shp" pip_lo_in_buf_sum_dbf = "E:/gina/poker/pip/pip_lo_in_buf_sum.dbf" pip_lo_in_buf_sum_csv = "E:/gina/poker/pip/pip_lo_in_buf_sum.csv" pip_popn_places_in_buffer_shp = "E:/gina/poker/pip/pip_popn_places_in_buffer.shp" pip_known_sites_in_buffer_shp = "E:/gina/poker/pip/pip_known_sites_in_buffer.shp" x = parameters[2].valueAsText y = parameters[3].valueAsText r = parameters[10].valueAsText + " NauticalMiles" rr1 = (float(parameters[10].valueAsText)) / 3 rr2 = (rr1 * 2) rrs = str(rr1) + ";" + str(rr2) + ";" + r.split(" ")[0] pipLayer = "pipLayer1" srs = arcpy.SpatialReference("Alaska Albers Equal Area Conic") intersect_fc1 = [adnr_lo_shp, pip_buffer_shp] intersect_fc2 = [pfrr_popn_places, pip_buffer_shp] intersect_fc3 = [afs_known_sites, pip_buffer_shp] mxd = arcpy.mapping.MapDocument("current") dataframe = arcpy.mapping.ListDataFrames(mxd)[0] sourceLoSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/lo2.lyr") sourcePipSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/pip2.lyr") sourceRrsSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/rrs.lyr") sourcePopSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/pop.lyr") sourceAfsSymbologyLayer = arcpy.mapping.Layer( "E:/gina/poker/lyr/afs2.lyr") # Process: Calculate Lon Field arcpy.CalculateField_management(pipTable, "Lon", x, "PYTHON", "") # Process: Calculate Lat Field arcpy.CalculateField_management(pipTable, "Lat", y, "PYTHON", "") # Process: Make XY Event Layer arcpy.MakeXYEventLayer_management( pipTable, "Lon", "Lat", pipLayer, "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119522E-09;0.001;0.001;IsHighPrecision", "") # Process: Copy Features arcpy.CopyFeatures_management(pipLayer, pip_point_shp, "", "0", "0", "0") # Process: Project pip point arcpy.Project_management(pip_point_shp, pip_point_3338, srs) # Process: Buffer pip point arcpy.Buffer_analysis(pip_point_3338, pip_buffer_shp, r, "FULL", "ROUND", "NONE", "", "PLANAR") # Process: Multiple Ring Buffer arcpy.MultipleRingBuffer_analysis(pip_point_3338, pip_range_rings_shp, rrs, "NauticalMiles", "", "NONE", "FULL") # Process: Intersect pip buffer with land ownership arcpy.Intersect_analysis(intersect_fc1, pip_lo_in_buffer_shp, "ALL", "", "INPUT") # Process: Intersect pip buffer with popn places arcpy.Intersect_analysis(intersect_fc2, pip_popn_places_in_buffer_shp, "ALL", "", "INPUT") # Process: Intersect pip buffer with afs known sites arcpy.Intersect_analysis(intersect_fc3, pip_known_sites_in_buffer_shp, "ALL", "", "INPUT") # Process: Make feature layers and add to the map ## pip feature class list fclist = arcpy.ListFeatureClasses() ## pip layer arcpy.MakeFeatureLayer_management(pip_point_3338, "Predicted Impact Point") ## land ownership layer arcpy.MakeFeatureLayer_management( pip_lo_in_buffer_shp, "Land Ownership within 3sigma of Predicted Impact Point") ## Range Rings arcpy.MakeFeatureLayer_management(pip_range_rings_shp, "Range Rings") ## populated places layer popn_places_records = int( arcpy.GetCount_management(pip_popn_places_in_buffer_shp).getOutput( 0)) if popn_places_records > 0: arcpy.MakeFeatureLayer_management( pip_popn_places_in_buffer_shp, "Populated Places within 3sigma of Predicted Impact Point") addPipPopnPlacesLayer = arcpy.mapping.Layer( "Populated Places within 3sigma of Predicted Impact Point") arcpy.mapping.AddLayer(dataframe, addPipPopnPlacesLayer) ## known sites layer known_sites_records = int( arcpy.GetCount_management(pip_known_sites_in_buffer_shp).getOutput( 0)) if known_sites_records > 0: arcpy.MakeFeatureLayer_management( pip_known_sites_in_buffer_shp, "AFS Known Sites within 3sigma of Predicted Impact Point") addPipKnownSitesLayer = arcpy.mapping.Layer( "AFS Known Sites within 3sigma of Predicted Impact Point") arcpy.mapping.AddLayer(dataframe, addPipKnownSitesLayer) addPipPointLayer = arcpy.mapping.Layer("Predicted Impact Point") arcpy.mapping.AddLayer(dataframe, addPipPointLayer) add3sigmaLoLayer = arcpy.mapping.Layer( "Land Ownership within 3sigma of Predicted Impact Point") arcpy.mapping.AddLayer(dataframe, add3sigmaLoLayer) addRangeRings = arcpy.mapping.Layer("Range Rings") arcpy.mapping.AddLayer(dataframe, addRangeRings) # Add and calc Acres field for intersected Land Ownership arcpy.AddField_management(pip_lo_in_buffer_shp, "Acres", "DOUBLE") arcpy.CalculateField_management(pip_lo_in_buffer_shp, "Acres", "!shape.area@acres!", "PYTHON_9.3", "") # Summarize intersected Land Ownership by Owner and total Acres arcpy.Statistics_analysis(pip_lo_in_buffer_shp, pip_lo_in_buf_sum_dbf, "Acres SUM", "OWNER") arcpy.MakeTableView_management(pip_lo_in_buf_sum_dbf) add3sigmaLoSumTbl = arcpy.mapping.TableView(pip_lo_in_buf_sum_dbf) arcpy.mapping.AddTableView(dataframe, add3sigmaLoSumTbl) # Symbolize and Refresh lo_layer = arcpy.mapping.ListLayers( mxd, "*Land Ownership within 3sigma of Predicted Impact Point*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, lo_layer, sourceLoSymbologyLayer, True) lo_layer.symbology.addAllValues() pip_layer = arcpy.mapping.ListLayers(mxd, "*Predicted Impact Point*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, pip_layer, sourcePipSymbologyLayer, True) rr_layer = arcpy.mapping.ListLayers(mxd, "*Range Rings*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, rr_layer, sourceRrsSymbologyLayer, True) pop_layer = arcpy.mapping.ListLayers(mxd, "*Populated Places*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, pop_layer, sourcePopSymbologyLayer, True) afs_layer = arcpy.mapping.ListLayers(mxd, "*Known Sites*", dataframe)[0] arcpy.mapping.UpdateLayer(dataframe, afs_layer, sourceAfsSymbologyLayer, True) arcpy.RefreshTOC() arcpy.RefreshActiveView() # Populate Mission GDB mission_layers = [ pip_point_3338, pip_lo_in_buffer_shp, pip_popn_places_in_buffer_shp, pip_range_rings_shp, pip_known_sites_in_buffer_shp ] arcpy.FeatureClassToGeodatabase_conversion(mission_layers, arcpy.env.workspace) return
#------------------------------------------------------------------------------- # Name: Refresh TOC/Map # Purpose: # # Author: chrism # # Created: 12/01/2017 # Copyright: (c) chrism 2017 # Licence: <your licence> #------------------------------------------------------------------------------- import arcpy mxd = arcpy.mapping.MapDocument("CURRENT") arcpy.RefreshActiveView()
import arcpy as arc from arcpy import env env.workspace = "C:/EsriTraining/MapScripting/Westerville.gdb" #specify which mapping document you want mxd = arc.mapping.MapDocument( "C:/EsriTraining/MapScripting/Exercise2/Westerville.mxd") #create list of data frame df = arc.mapping.ListDataFrames(mxd)[0] #create list of layers lyr = arc.mapping.ListLayers(mxd, "", df)[0] lyr.visible = True print(lyr) arc.RefreshActiveView() arc.RefreshTOC()
def generate_atlas(self): """ Assigned to Michael Cope """ for intensity_raster in os.listdir(self.rasters_folder_path): if os.path.isdir(self.rasters_folder_path + intensity_raster ) and intensity_raster.endswith('_i'): arcpy.AddMessage( "Creating PDF for event {0}".format(intensity_raster)) event_id = intensity_raster[:-2] mxd = arcpy.mapping.MapDocument(self.pdf_template) # lists the current dataframes in the mxd file and selects the first one df = arcpy.mapping.ListDataFrames(mxd)[0] # convert raster to a layer and add to the mxd file resultant_layer = arcpy.MakeRasterLayer_management( self.rasters_folder_path + intensity_raster, intensity_raster) result = arcpy.SaveToLayerFile_management( intensity_raster, self.layers_folder_path + intensity_raster) extent_layer = arcpy.MakeRasterLayer_management( self.rasters_folder_path + event_id, event_id) # Apply symbology arcpy.ApplySymbologyFromLayer_management( resultant_layer, self.symbology_layer) layerfile = resultant_layer.getOutput(0) extent_layerfile = extent_layer.getOutput(0) arcpy.mapping.AddLayer(df, layerfile, "AUTO_ARRANGE") arcpy.mapping.AddLayer(df, extent_layerfile, "AUTO_ARRANGE") # describe raster so it can zoom to area affected by earthquake selected_layer = arcpy.mapping.ListLayers( mxd, str(event_id), df)[0] df.extent = selected_layer.getSelectedExtent() # refresh the map and table of contents arcpy.RefreshActiveView() arcpy.RefreshTOC() for sleep in range(1000): pass # Hide all layers not associated with current event for layer in arcpy.mapping.ListLayers(mxd, "", df): try: if layer.name == event_id + "_i" or layer.name == 'World_Imagery': layer.visible = True else: layer.visible = False except: pass # Collect metadata for atlas page title = 'USGS Event Code: {0}'.format(event_id) magnitude = 'Magnitude: {0}'.format( self.event_metadata[str(event_id)]['magnitude']) lon = 'Longitude: {0}'.format( self.event_metadata[str(event_id)]['lon']) lat = 'Latitude: {0}'.format( self.event_metadata[str(event_id)]['lat']) date = 'Date: {0}'.format( self.event_metadata[str(event_id)]['date']) # Add metadata to map for elem in arcpy.mapping.ListLayoutElements( mxd, "TEXT_ELEMENT"): if elem.text == "Title": elem.text = title elif elem.text == "Magnitude": elem.text = magnitude elif elem.text == "Longitude": elem.text = lon elif elem.text == "Latitude": elem.text = lat elif elem.text == "Date": elem.text = date # refresh the map and table of contents arcpy.RefreshActiveView() arcpy.RefreshTOC() for sleep in range(1000): pass current_pdf = self.temp_folder + '\\' + event_id + '.pdf' # Export current atlas page to pdf arcpy.mapping.ExportToPDF( mxd, current_pdf) # exports current layout to a new pdf # Revert element tags for elem in arcpy.mapping.ListLayoutElements( mxd, "TEXT_ELEMENT"): if elem.text == title: elem.text = "Title" elif elem.text == magnitude: elem.text = "Magnitude" elif elem.text == lon: elem.text = "Longitude" elif elem.text == lat: elem.text = "Latitude" elif elem.text == date: elem.text = "Date" # Append atlas page to final report self.pdfDoc.appendPages(str(current_pdf))
def make_arcpy_maps(): LOCATOR_SCALE = 1875 GRID_SCALE = 125 output_dir = 'C:/' _gis_dir = 'C:/' env.overwriteOutput = True env.workspace = os.path.join(_gis_dir,'maps/') map_template = os.path.join(env.workspace, 'grid_template.mxd') mxd = arcpy.mapping.MapDocument(map_template) # Target and tmp grid target paths tmp_grid_trg_path = os.path.join(_gis_dir,'tmp/temp_grid_targets.shp') master_trg_path = arcpy.mapping.Layer(os.path.join(env.workspace,'master_targets.lyr')) target_template = arcpy.mapping.Layer(os.path.join(env.workspace, 'target_template.lyr')) rgb_template_layer = arcpy.mapping.Layer(os.path.join(env.workspace, 'raster_template.lyr')) grid_ids = get_grid_ids() raster_names = [os.path.basename(i).split('_')[0] for i in grid_ids] for r, curr_grid_id in enumerate(grid_ids): print "Grid_ID = '%(grid)s'" % {"grid":raster_names[r]} grid_df = arcpy.mapping.ListDataFrames(mxd, 'Grid')[0] # Add master_target_shp arcpy.mapping.AddLayer(grid_df, master_trg_path, "TOP") # Select targets from master_target_lyr master_trg_layer = arcpy.mapping.ListLayers(mxd, 'Targeted Anomaly', grid_df) if len(master_trg_layer)>1: print master_trg_layer master_trg_layer=master_trg_layer[0] arcpy.SelectLayerByAttribute_management(master_trg_layer, "NEW_SELECTION", "\"Grid_ID\" = \'%(grid)s\'"%{"grid":raster_names[r]}) # Copy master_trg_layer selected targets and output to tmp_grid_trg_path shapefile. arcpy.CopyFeatures_management(master_trg_layer, tmp_grid_trg_path) # Remove master_target_lyr arcpy.mapping.RemoveLayer(grid_df, master_trg_layer) arcpy.mapping.RemoveLayer(grid_df, master_trg_layer) # Add temp shapefile to grid arcdf, reselect it from arcdf, and update layer tmp_grd_target_layer = arcpy.mapping.Layer(tmp_grid_trg_path) arcpy.mapping.AddLayer(grid_df, tmp_grd_target_layer, "TOP") tmp_grd_target_layer = arcpy.mapping.ListLayers(mxd, tmp_grd_target_layer, grid_df)[0] arcpy.mapping.UpdateLayer(grid_df, tmp_grd_target_layer, target_template, True) # Center grid dataframe on grid. map_extent = get_extent_from_stake_df(grid=raster_names[r]) grid_df.extent = map_extent grid_df.scale = GRID_SCALE tmp_grd_target_layer.extent = map_extent # Center locator dataframe on grid. locator_df = arcpy.mapping.ListDataFrames(mxd, 'Locator')[0] locator_df.extent = map_extent locator_df.scale = LOCATOR_SCALE # Update view and legend grid_df = arcpy.mapping.ListDataFrames(mxd, 'Grid')[0] legend_title = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", u'LegendTitle')[0] legend_title.text = 'GRID ' + raster_names[r] arcpy.RefreshActiveView() arcpy.RefreshTOC() print 'Exporting pdf for ' + raster_names[r] output_pdf = os.path.join(output_dir, raster_names[r]+'.pdf') arcpy.mapping.ExportToPDF(mxd, output_pdf, data_frame="PAGE_LAYOUT", layers_attributes="LAYERS_ONLY", georef_info=True, picture_symbol='VECTORIZE_BITMAP', convert_markers=True, jpeg_compression_quality=76, resolution=160)
global mapbook mapbook = arcpy.mapping.PDFDocumentCreate(mapbookpath) arcpy.AddMessage("Creating final mapbook PDF at "+ mapbookpath) for mxd in mxdList: mapdoc = arcpy.mapping.MapDocument(mxd) mxdname=basename(mxd) # get mxd name arcpy.AddMessage("Working on "+ mxdname) mapdoccopy=outpath+"/"+mxdname mapdoc.saveACopy(mapdoccopy) # copy template mxd to output directory mapdoc = arcpy.mapping.MapDocument(mapdoccopy) mapdoc.title=mxdname # set mapdoc title to match input mxdname mapdoc.save() # save mapdoc for df in arcpy.mapping.ListDataFrames(mapdoc): global mapbook # call global variable inside loop mapdoc.activeview='PAGE_LAYOUT' # set mapdoc view to layout view arcpy.RefreshActiveView() # refresh dataframe view par=arcpy.mapping.ListLayers(mapdoc,"*Parcel*",df)[0] # get parcel layer from dataframe arcpy.SelectLayerByLocation_management(par,"intersect",outpath+"/bffr.shp") # select parcels in mxd that intersect recently certified parcels selected arcpy.AddMessage("Selecting parcels in " + mxdname+ " that intersect selected parcels in "+mxdList[-1]) par.showLabels = True # turn on PID labels df.zoomToSelectedFeatures() # zoom to selected parcels that intersect merged buffer arcpy.RefreshActiveView() # refresh dataframe view df_pdf = outpath+'/'+df.name+".pdf" # create pdf file name in outpath with dataframe name (which should be year) arcpy.AddMessage("Overwriting "+df_pdf+" if already existed") silentremove(df_pdf) # delete intermediate pdf if already exists ## if 'Include Aerials?" = true (checked), do this if str(ischecked) == 'true': aerialDir = r"\\bcad90\doqq\Bexar_Aerial_Mosaics" # Directory with Bexar County aerial mosaics aerialGDB = aerialDir+r"\Bexar_Aerial_Mosaics.gdb" # gdb inside aerial directory with aerial mosaics arcpy.env.workspace = aerialGDB # set env.workspace to aerial gdb in_mosaicdataset_name = r"\bexarMosaics_"+df.name # input mosaic dataset name as bexarMosaics_[year], following naming convention in gdb
def createWORD(app): infomatrix = [] directory = os.path.join(viewer_path, OrderNumText, 'fin') i = 0 items = os.listdir(directory) for i in range(0, len(items)): item = items[i] if item.lower() == 'thumbs.db' or item.lower() == '_aux' or item.lower( ) == '_bndry' or item.lower() == '_del' or "jpg" not in item[-4:]: continue year = item.split('.')[0].split('_')[0] source = item.split('.')[0].split('_')[1] scale = int(item.split('.')[0].split('_')[2]) * 12 if len(item.split('.')[0].split('_')) > 3: comment = item.split('.')[0].split('_')[3] else: comment = '' infomatrix.append((item, year, source, scale, comment)) if OrderType.lower() == 'point': orderGeomlyrfile = orderGeomlyrfile_point elif OrderType.lower() == 'polyline': orderGeomlyrfile = orderGeomlyrfile_polyline else: orderGeomlyrfile = orderGeomlyrfile_polygon orderGeomLayer = arcpy.mapping.Layer(orderGeomlyrfile) orderGeomLayer.replaceDataSource(scratch, "SHAPEFILE_WORKSPACE", "orderGeometry") if os.path.exists(os.path.join(scratch, 'tozip')): shutil.rmtree(os.path.join(scratch, 'tozip')) shutil.copytree(directorytemplate, os.path.join(scratch, 'tozip')) # add to map template, clip (but need to keep both metadata: year, grid size, quadrangle name(s) and present in order mxd = arcpy.mapping.MapDocument(mxdfile) df = arcpy.mapping.ListDataFrames(mxd, "*")[0] spatialRef = arcpy.SpatialReference(out_coordinate_system) df.spatialReference = spatialRef #if OrderType.lower() == "polyline" or OrderType.lower() == "polygon": # arcpy.mapping.AddLayer(df,orderGeomLayer,"Top") if OrderType.lower() == "polyline" or OrderType.lower() == "polygon": if yesBoundary.lower() == 'y' or yesBoundary.lower() == 'yes': arcpy.mapping.AddLayer(df, orderGeomLayer, "Top") infomatrix_sorted = sorted(infomatrix, key=operator.itemgetter(1, 0), reverse=True) for i in range(0, len(infomatrix_sorted)): imagename = infomatrix_sorted[i][0] year = infomatrix_sorted[i][1] source = infomatrix_sorted[i][2] scale = infomatrix_sorted[i][3] comment = infomatrix_sorted[i][4] ## for lyr in arcpy.mapping.ListLayers(mxd, "Project Property", df): ## if lyr.name == "Project Property": ## if OrderType.lower() == "point": ## lyr.visible = False ## else: ## lyr.visible = True ## df.extent = lyr.getSelectedExtent(False) for lyr in arcpy.mapping.ListLayers(mxd, "Project Property", df): if lyr.name == "Project Property": if OrderType.lower() == "point": lyr.visible = False else: lyr.visible = True df.extent = lyr.getExtent(True) #centerlyr = arcpy.mapping.Layer(orderCenter) #centerlyr = arcpy.MakeFeatureLayer_management(orderCenter, "center_lyr") #arcpy.mapping.AddLayer(df,centerlyr,"Top") #center = arcpy.mapping.ListLayers(mxd, "*", df)[0] #df.extent = center.getSelectedExtent(False) #center.visible = False df.scale = scale arcpy.RefreshTOC() arcpy.RefreshActiveView() outputemf = os.path.join(scratch, year + ".emf") print outputemf arcpy.mapping.ExportToEMF(mxd, outputemf, "PAGE_LAYOUT") mxd.saveACopy(os.path.join(scratch, year + "_emf.mxd")) shutil.copyfile(os.path.join(directory, imagename), os.path.join(scratch, "tozip\word\media\image2.jpeg")) shutil.copyfile(os.path.join(scratch, year + ".emf"), os.path.join(scratch, "tozip\word\media\image1.emf")) zipdir_noroot(os.path.join(scratch, 'tozip'), year + ".docx") worddoclist.append(os.path.join(scratch, year + ".docx")) #the word template has been copied, the image files have also been copied, need to refresh and replace the text fields, save doc = app.Documents.Open(os.path.join(scratch, year + ".docx")) fileName = OrderNumText fileDate = time.strftime('%Y-%m-%d', time.localtime()) #quads = 'AERIAL PHOTOGRAPHY FROM SOURCE ' + source + '(' +str(year) + ')' quads = '' if scale == 6000: scaletxt = '1":' + str(scale / 12) + "'" #scaletxt = '1:' + str(scale) else: scaletxt = '1:' + str(scale) allShapes = doc.Shapes allShapes(3).TextFrame.TextRange.Text = 'AERIAL PHOTO (' + str( year) + '-' + source + ')' #AERIAL PHOTOGRAPH line txt = allShapes(4).TextFrame.TextRange.Text.replace( 'Site Name', siteName) #allShapes(4).TextFrame.TextRange.Text.replace('Site Address', siteAddress) #allShapes(4).TextFrame.TextRange.Text.replace('Site City, Site State', siteCityState) txt = txt.replace('Site Address', siteAddress) txt = txt.replace('Site City, Site State', siteCityState) if not custom_profile: allShapes(4).TextFrame.TextRange.Text = txt allShapes(9).TextFrame.TextRange.Text = quads allShapes(11).TextFrame.TextRange.Text = officeAddress allShapes(12).TextFrame.TextRange.Text = officeCity allShapes(13).TextFrame.TextRange.Text = proNo ## allShapes(26).TextFrame.TextRange.Text = scaletxt ## allShapes(27).TextFrame.TextRange.Text = fileName ## allShapes(28).TextFrame.TextRange.Text = fileDate ## allShapes(13).TextFrame.TextRange.Text = proNo allShapes(23).TextFrame.TextRange.Text = scaletxt #good allShapes(24).TextFrame.TextRange.Text = fileName #good allShapes(25).TextFrame.TextRange.Text = fileDate #good else: allShapes(4).TextFrame.TextRange.Text = txt allShapes(9).TextFrame.TextRange.Text = quads allShapes(11).TextFrame.TextRange.Text = officeAddress allShapes(12).TextFrame.TextRange.Text = officeCity allShapes(13).TextFrame.TextRange.Text = proNo ## allShapes(26).TextFrame.TextRange.Text = scaletxt ## allShapes(27).TextFrame.TextRange.Text = fileName ## allShapes(28).TextFrame.TextRange.Text = fileDate ## allShapes(13).TextFrame.TextRange.Text = proNo allShapes(23).TextFrame.TextRange.Text = scaletxt #good allShapes(24).TextFrame.TextRange.Text = fileName #good allShapes(25).TextFrame.TextRange.Text = fileDate #good doc.Save() doc.Close() doc = None del mxd return infomatrix_sorted