def main(): """ Runs the centrality tool. """ env.overwriteOutput = True # Enable overwritting CheckOutExtension("Network") # Success of the program through the six steps success = True # Inputs to the tool if len(argv) != INPUT_COUNT + 1: raise Exception("Invalid number of inputs") input_number = index() input_number.next() # Skip over sys.argv[0] inputs = {} inputs[INPUT_BUILDINGS] = argv[input_number.next()] inputs[POINT_LOCATION] = ("INSIDE" if argv[input_number.next()] == "true" else "CENTROID") inputs[INPUT_NETWORK] = argv[input_number.next()] inputs[COMPUTE_REACH] = argv[input_number.next()] == "true" inputs[COMPUTE_GRAVITY] = argv[input_number.next()] == "true" inputs[COMPUTE_BETWEENNESS] = argv[input_number.next()] == "true" inputs[COMPUTE_CLOSENESS] = argv[input_number.next()] == "true" inputs[COMPUTE_STRAIGHTNESS] = argv[input_number.next()] == "true" inputs[ID_ATTRIBUTE] = argv[input_number.next()] inputs[NODE_WEIGHT_ATTRIBUTE] = argv[input_number.next()] inputs[IMPEDANCE_ATTRIBUTE] = argv[input_number.next()] try: inputs[SEARCH_RADIUS] = float(argv[input_number.next()]) except: inputs[SEARCH_RADIUS] = INFINITE_RADIUS inputs[USE_NETWORK_RADIUS] = (argv[input_number.next()] == ON_THE_NETWORK_OPTION) try: inputs[BETA] = float(argv[input_number.next()]) except: raise Invalid_Input_Exception("Beta") inputs[NORMALIZE_RESULTS] = [measure for measure in argv[input_number.next()].split(";") if measure != "#"] inputs[OUTPUT_LOCATION] = argv[input_number.next()] inputs[OUTPUT_FILE_NAME] = argv[input_number.next()] inputs[ACCUMULATOR_ATTRIBUTES] = argv[input_number.next()] # Record the origin nodes for centrality measurements # This is important if the user selects a subset of the features to be origins selected_features = all_values_in_column(inputs[INPUT_BUILDINGS], inputs[ID_ATTRIBUTE]) # Clear selection if we got a layer file try: SelectLayerByAttribute_management(inputs[INPUT_BUILDINGS], "CLEAR_SELECTION") except: pass # Adjacency List table name node_locations_needed = (inputs[COMPUTE_STRAIGHTNESS] or not inputs[USE_NETWORK_RADIUS]) adj_dbf_name = ("%s_%s_%s_%s_%s_%s.dbf" % (ADJACENCY_LIST_NAME, basename(inputs[INPUT_BUILDINGS]), basename(inputs[INPUT_NETWORK]), inputs[ID_ATTRIBUTE], inputs[IMPEDANCE_ATTRIBUTE], inputs[ACCUMULATOR_ATTRIBUTES])).replace("#", "None") if len(adj_dbf_name) > MAX_FILE_NAME_LENGTH: AddWarning(WARNING_LARGE_ADJ_FILE_NAME) adj_dbf = join(inputs[OUTPUT_LOCATION], adj_dbf_name) # Output file names output_feature_class_name = feature_class_name(inputs[OUTPUT_FILE_NAME]) output_feature_class = "%s.shp" % join(inputs[OUTPUT_LOCATION], output_feature_class_name) # Create a feature class that is a copy of the input buildings try: AddMessage(INPUT_BUILDINGS_COPY_STARTED) CreateFeatureclass_management(out_path=inputs[OUTPUT_LOCATION], out_name=output_feature_class_name) CopyFeatures_management(in_features=inputs[INPUT_BUILDINGS], out_feature_class=output_feature_class) AddMessage(INPUT_BUILDINGS_COPY_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(INPUT_BUILDINGS_COPY_FAILED) success = False output_layer_name = layer_name(inputs[OUTPUT_FILE_NAME]) output_layer = "%s.lyr" % join(inputs[OUTPUT_LOCATION], output_layer_name) # If output has already been created, don't carry on if Exists(output_layer): AddWarning(WARNING_OUTPUT_ALREADY_EXISTS) success = False # We will convert polygon input buildings to point feature class buildings_description = Describe(output_feature_class) if buildings_description.shapeType == "Point": # Input buildings are already a point shape file inputs[INPUT_POINTS] = output_feature_class elif buildings_description.shapeType == "Polygon": # Input buildings need to be converted to point feature class point_feature_class_name = POINT_FEATURE_CLASS_NAME( basename(output_feature_class), inputs[POINT_LOCATION]) inputs[INPUT_POINTS] = "%s.shp" % join(inputs[OUTPUT_LOCATION], point_feature_class_name) # If FID is used as ID attribute, we need to change it since a point # shapefile will be in use if inputs[ID_ATTRIBUTE] == "FID": inputs[ID_ATTRIBUTE] = ORIGINAL_FID else: # Input buildings need to be either points or polygons raise Invalid_Input_Exception("Input Buildings") # Find the appropriate symbology layer for metric_index in range(len(METRICS)): if inputs[COMPUTE_REACH + metric_index]: first_metric = METRICS[metric_index] break symbology_layer_name = get_symbology_layer_name( buildings_description.shapeType, first_metric) symbology_layer = join(SYMBOLOGY_DIR, symbology_layer_name) def clean_up(): """ Removes all auxiliary files """ auxiliary_dir = join(inputs[OUTPUT_LOCATION], AUXILIARY_DIR_NAME) od_cost_matrix_layer = join(auxiliary_dir, OD_COST_MATRIX_LAYER_NAME) od_cost_matrix_lines = join(auxiliary_dir, OD_COST_MATRIX_LINES) temp_adj_dbf_name = "%s~.dbf" % adj_dbf_name[-4] temp_adj_dbf = join(inputs[OUTPUT_LOCATION], temp_adj_dbf_name) partial_adj_dbf = join(auxiliary_dir, PARTIAL_ADJACENCY_LIST_NAME) polygons = join(auxiliary_dir, POLYGONS_SHAPEFILE_NAME) raster = join(auxiliary_dir, RASTER_NAME) polygons_layer = join(auxiliary_dir, POLYGONS_LAYER_NAME) input_points_layer = join(auxiliary_dir, INPUT_POINTS_LAYER_NAME) for delete_path in [input_points_layer, polygons_layer, raster, polygons, partial_adj_dbf, temp_adj_dbf, od_cost_matrix_lines, od_cost_matrix_layer, auxiliary_dir]: delete(delete_path) try: """ Here we carry out the six steps of the tool """ # Step 1 if success: AddMessage(STEP_1_STARTED) # If necessary, convert input buildings to point feature class if buildings_description.shapeType == "Polygon": AddMessage(POINT_CONVERSION_STARTED) to_point_feature_class(output_feature_class, inputs[INPUT_POINTS], inputs[POINT_LOCATION]) AddMessage(POINT_CONVERSION_FINISHED) if Exists(adj_dbf): AddMessage(ADJACENCY_LIST_COMPUTED) if node_locations_needed: calculate_network_locations(inputs[INPUT_POINTS], inputs[INPUT_NETWORK]) AddMessage(STEP_1_FINISHED) else: try: compute_adjacency_list(inputs[INPUT_POINTS], inputs[INPUT_NETWORK], inputs[ID_ATTRIBUTE], inputs[IMPEDANCE_ATTRIBUTE], inputs[ACCUMULATOR_ATTRIBUTES], inputs[SEARCH_RADIUS], inputs[OUTPUT_LOCATION], adj_dbf_name) AddMessage(STEP_1_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_1_FAILED) success = False # Step 2 if success: AddMessage(STEP_2_STARTED) try: distance_field = trim("Total_%s" % inputs[IMPEDANCE_ATTRIBUTE]) accumulator_fields = set([trim("Total_%s" % accumulator_attribute) for accumulator_attribute in inputs[ACCUMULATOR_ATTRIBUTES].split( ";") if accumulator_attribute != "#"]) # Graph representation: dictionary mapping node id's to Node objects nodes = {} # The number of rows in |adj_dbf| directed_edge_count = int(GetCount_management(adj_dbf).getOutput(0)) graph_progress = Progress_Bar(directed_edge_count, 1, STEP_2) rows = UpdateCursor(adj_dbf) for row in rows: # Get neighboring nodes, and the distance between them origin_id = row.getValue(trim(ORIGIN_ID_FIELD_NAME)) destination_id = row.getValue(trim(DESTINATION_ID_FIELD_NAME)) distance = float(row.getValue(distance_field)) # Make sure the nodes are recorded in the graph for id in [origin_id, destination_id]: if not id in nodes: nodes[id] = Node() # Make sure that the nodes are neighbors in the graph if origin_id != destination_id and distance >= 0: accumulations = {} for field in accumulator_fields: accumulations[field] = float(row.getValue(field)) nodes[origin_id].add_neighbor(destination_id, distance, accumulations) nodes[destination_id].add_neighbor(origin_id, distance, accumulations) graph_progress.step() N = len(nodes) # The number of nodes in the graph if N == 0: AddWarning(WARNING_NO_NODES) success = False AddMessage(STEP_2_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_2_FAILED) success = False # Step 3 if success: AddMessage(STEP_3_STARTED) try: get_weights = inputs[NODE_WEIGHT_ATTRIBUTE] != "#" get_locations = node_locations_needed # Keep track of number nodes in input points not present in the graph point_not_in_graph_count = 0 input_point_count = int( GetCount_management(inputs[INPUT_POINTS]).getOutput(0)) node_attribute_progress = Progress_Bar(input_point_count, 1, STEP_3) rows = UpdateCursor(inputs[INPUT_POINTS]) for row in rows: id = row.getValue(inputs[ID_ATTRIBUTE]) if not id in nodes: point_not_in_graph_count += 1 continue if get_weights: setattr(nodes[id], WEIGHT, row.getValue(trim(inputs[NODE_WEIGHT_ATTRIBUTE]))) if get_locations: snap_x = row.getValue(trim("SnapX")) snap_y = row.getValue(trim("SnapY")) setattr(nodes[id], LOCATION, (snap_x, snap_y)) node_attribute_progress.step() if point_not_in_graph_count: AddWarning(WARNING_POINTS_NOT_IN_GRAPH(N, point_not_in_graph_count)) AddMessage(STEP_3_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_3_FAILED) success = False # Step 4 if success: AddMessage(STEP_4_STARTED) try: # Compute measures compute_centrality(nodes, selected_features, inputs[COMPUTE_REACH], inputs[COMPUTE_GRAVITY], inputs[COMPUTE_BETWEENNESS], inputs[COMPUTE_CLOSENESS], inputs[COMPUTE_STRAIGHTNESS], inputs[SEARCH_RADIUS], inputs[USE_NETWORK_RADIUS], inputs[BETA], inputs[NORMALIZE_RESULTS], accumulator_fields) AddMessage(STEP_4_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_4_FAILED) success = False # Step 5 if success: AddMessage(STEP_5_STARTED) try: # Make output layer MakeFeatureLayer_management(in_features=output_feature_class, out_layer=output_layer_name) # Save output layer SaveToLayerFile_management(output_layer_name, output_layer, "ABSOLUTE") # Use a test node to figure out which metrics were computed test_node_id = selected_features.pop() # Make sure the test node is in the graph while test_node_id not in nodes: test_node_id = selected_features.pop() test_node = nodes[test_node_id] measures = set([measure for measure in dir(test_node) if (measure in FINAL_ATTRIBUTES or is_accumulator_field(measure))]) # Add a field in the output layer for each computed metric for measure in measures: AddField_management(in_table=output_layer, field_name=trim(measure), field_type="DOUBLE", field_is_nullable="NON_NULLABLE") # Figure out the id field to use based on the type of input buildings if (buildings_description.shapeType == "Polygon" and inputs[ID_ATTRIBUTE] == ORIGINAL_FID): id_field = "FID" else: id_field = inputs[ID_ATTRIBUTE] # Fill the layer with the metric values write_progress = Progress_Bar(N, 1, STEP_5) layer_rows = UpdateCursor(output_layer) for row in layer_rows: id = row.getValue(id_field) for measure in measures: # If no value was computed for this node id, set value to 0 value = 0 if id in nodes and hasattr(nodes[id], measure): value = getattr(nodes[id], measure) row.setValue(trim(measure), value) layer_rows.updateRow(row) write_progress.step() # Save to toolbox output SetParameterAsText(OUTPUT_FEATURE_CLASS, output_feature_class) AddMessage(STEP_5_FINISHED) except: AddWarning(GetMessages(2)) AddMessage(STEP_5_FAILED) success = False # Step 6 if success: AddMessage(STEP_6_STARTED) # Apply symbology try: ApplySymbologyFromLayer_management(in_layer=output_layer, in_symbology_layer=symbology_layer) except: AddWarning(WARNING_APPLY_SYMBOLOGY_FAILED) AddWarning(GetMessages(2)) AddMessage(STEP_6_FAILED) # Display try: current_map_document = mapping.MapDocument("CURRENT") data_frame = mapping.ListDataFrames(current_map_document, "Layers")[0] add_layer = mapping.Layer(output_layer) mapping.AddLayer(data_frame, add_layer, "AUTO_ARRANGE") AddMessage(STEP_6_FINISHED) except: AddWarning(WARNING_FAIL_TO_DISPLAY) AddWarning(GetMessages(2)) AddMessage(STEP_6_FAILED) # Clean up clean_up() AddMessage(SUCCESS if success else FAILURE) except ExecuteAbort: clean_up()
# Author: ESRI # Date: July 5, 2010 # Version: ArcGIS 10.0 # Purpose: This script generates a report of each page layout element and its # associated properties. This script is intended to run as a scrip tool # and requires two parameters: # 1) Output text file. import arcpy, os, datetime, arcpy.mapping as MAP #Read parameters from tool #mxdPath = arcpy.GetParameterAsText(0) output = arcpy.GetParameterAsText(0) MXD = MAP.MapDocument("CURRENT") try: #Create r/w output file outFile = open(output, "w") #Generate Report header outFile.write("PageLayout Element Report: \n") outFile.write("\n") outFile.write("This report lists the properties of invidual page layout elements within a single MXD. \n") outFile.write("\n") outFile.write("MXD location: " + MXD.filePath + "\n") outFile.write("\n") outFile.write("Date: " + str(datetime.datetime.today().strftime("%B %d, %Y")) + "\n") outFile.write("\n") #Reference MXD file
import arcpy.mapping as mapping mxd = mapping.MapDocument("CURRENT") frames = mapping.ListDataFrames(mxd, "L*") for df in frames: print df.name
import arcpy.mapping as mapping, os path = r"C:" f = open(r"C:\Users\jastepha\Desktop\BrokenDataList.txt", 'w') for root, dirs, files in os.walk(path): for filename in files: basename, extension = os.path.splitext(filename) if extension == ".mxd": fullPath = os.path.join(path, filename) mxd = mapping.MapDocument(fullPath) f.write("MXD: " + filename + "\n") brknList = mapping.ListBrokenDataSources(mxd) for brknItem in brknList: f.write("\t" + brknItem.name + "\n") f.close()
# # Displays current conditions (species likelihood averaged across all indicator # species) in the current map. Classes are set as deciles with a user range of # values removed from the decile computation (to eliminate zeros). # # Jan 2016, [email protected] import sys, os, arcpy from arcpy import mapping as mp #Paths scriptDir = os.path.dirname(sys.argv[0]) rootDir = os.path.dirname(scriptDir) #Inputs mxd = mp.MapDocument(os.path.join(rootDir,"HabitatPrioritizationTool.mxd")) ecoregion = "Piedmont" scenario = "BF" scenarioFC = os.path.join(rootDir,"Data\\{0}\\{1}_Uplift.gdb\\{1}_Uplift03050102".format(ecoregion,scenario)) baseLyrFile = os.path.join(scriptDir,"LyrFiles","CurrentConditionsBase.lyr") # ---Functions--- def msg(txt,type="message"): print txt if type == "message": arcpy.AddMessage(txt) elif type == "warning": arcpy.AddWarning(txt) elif type == "error": arcpy.AddError(txt)
def MXDtoFeatureServiceDef( mxd_path, service_name=None, tags=None, description=None, folder_name=None, capabilities ='Query,Create,Update,Delete,Uploads,Editing,Sync', maxRecordCount=1000, server_type='MY_HOSTED_SERVICES', url='http://www.arcgis.com'): """ converts an MXD to a service defenition Inputs: mxd_path - Path to the ArcMap Map Document(MXD) service_name - Name of the Feature Service tags - Tags for the service, if none, the tags from the MXD are used description - Summary for the Feature Service, if none, info from the MXD is used folder_name - Folder in the Data store capabilities - A Comma delimited list of feature service capabolities 'Query,Create,Update,Delete,Uploads,Editing,Sync' maxRecordCount - The max returned record count for the feature service server_type - The type of connection or publishing server Values: ARCGIS_SERVER | FROM_CONNECTION_FILE | SPATIAL_DATA_SERVER | MY_HOSTED_SERVICES Output: Service Definition File - *.sd """ if not os.path.isabs(mxd_path): sciptPath = os.getcwd() mxd_path = os.path.join(sciptPath,mxd_path) mxd = mapping.MapDocument(mxd_path) sddraftFolder = env.scratchFolder + os.sep + "draft" sdFolder = env.scratchFolder + os.sep + "sd" sddraft = sddraftFolder + os.sep + service_name + ".sddraft" sd = sdFolder + os.sep + "%s.sd" % service_name mxd = _prep_mxd(mxd) res = {} if service_name is None: service_name = mxd.title.strip().replace(' ','_') if tags is None: tags = mxd.tags.strip() if description is None: description = mxd.description.strip() if os.path.isdir(sddraftFolder) == False: os.makedirs(sddraftFolder) else: shutil.rmtree(sddraftFolder, ignore_errors=True) os.makedirs(sddraftFolder) if os.path.isfile(sddraft): os.remove(sddraft) res['service_name'] = service_name res['tags'] = tags res['description'] = description analysis = mapping.CreateMapSDDraft(map_document=mxd, out_sddraft=sddraft, service_name=service_name, server_type=server_type, connection_file_path=None, copy_data_to_server=True, folder_name=folder_name, summary=description, tags=tags) sddraft = _modify_sddraft(sddraft=sddraft, capabilities=capabilities, maxRecordCount=maxRecordCount, url=url) analysis = mapping.AnalyzeForSD(sddraft) if os.path.isdir(sdFolder): shutil.rmtree(sdFolder, ignore_errors=True) os.makedirs(sdFolder) else: os.makedirs(sdFolder) if analysis['errors'] == {}: # Stage the service arcpy.StageService_server(sddraft, sd) res['servicedef'] = sd return res else: # If the sddraft analysis contained errors, display them and quit. print analysis['errors'] return None
# Licence: <your licence> #------------------------------------------------------------------------------- '''In this recipe, you will learn how to recursively search directories for map document files, find any broken data sources within these map documents, and write the names of the broken data layers to a file.''' # import the module import arcpy.mapping as mapping, os # open a file for writing broken layer names f = open('BrokenDataList.txt', 'w') # use os.walk() method with a path and a for loop for walking directory tree for root, dirs, files in os.walk("C:\ArcPyBook"): # create a second for loop that loops through all files returned and # create a new filename variable for name in files: filename = os.path.join(root, name) # test the file extension to see if it is a # map document file. If so, create a new map document object instance using the path, # write the map document name, get a list of broken data sources, loop through each # of the broken data sources, and write to the file if ".mxd" in filename: mxd = mapping.MapDocument(filename) f.write("MXD: " + filename + "\n") brknList = mapping.ListBrokenDataSources(mxd) for brknItem in brknList: "Broken data item: " + brknItem.name + " in " + filename f.write("\t" + brknItem.name + "\n") print("All Done") f.close()
#Original strInFileDirectory = raw_input("In Directory: ") strOutFileDirectory = raw_input("Out Directory: ") count = 0 for (dirname, dirs, files) in os.walk(strInFileDirectory): # print dirname # print dirs # print files # print "\n" # print dirname for filename in files: if filename.endswith(".mxd"): # & count <= 1 #Needed to first rename the files to be distinct by adding the data date. Did this just once. # strNewName = dirname[-8:] + filename # os.rename(os.path.join(dirname,filename),os.path.join(dirname,strNewName)) strMXDPath = os.path.join(dirname, filename) mapDoc = mapping.MapDocument(strMXDPath) strRootMXDName = filename[0:-4] + ".pdf" strNewPdfPath = os.path.join(strOutFileDirectory, strRootMXDName) try: mapping.ExportToPDF(map_document=mapDoc, out_pdf=strNewPdfPath) except: print "problem exporting to pdf" count += 1 print "MXD printed: {}, count={}".format(filename, count) del mapDoc print "All Done" sys.exit()
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())
metrics = [] # Setup metrics tracking list # iterate over the mxd's and augment file_list = list_directory_files(working_directory, '.mxd') map_count = 0 for f in file_list: # if map_count == 10: # break # # map_count += 1 metrics_row = [] # Create metrics row mxd_name = os.path.split(f)[1] # Extract mxd name metrics_row.append(mxd_name) mxd = mp.MapDocument(f) # open map doc df = mp.ListDataFrames(mxd)[ 0] # Select the first df as there is only 1 in each map # Add layers in new_layers to copied mdb and then create a list of the layers to then add to the map # Project the layers so that the sr's match sr = df.spatialReference print 'Checking to see if new layer falls within map extent' line_lyr = mp.Layer(new_geom_lines) overlap = checkForOverlap(df, workingGDB, line_lyr) metrics_row.append(overlap) if overlap is False: print 'New geometry does not fall within the map extent. Moving on to next map.' metrics.append(metrics_row) continue # If the overlap is false then skip exporting it
matrix[i][j] = -999.0 #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'):
sheetCount = 1 #count for each mxd allCount = 3 #count for first sheet including all sources #Sheet and column names for all data sources (first sheet) ws = wb.create_sheet("Alla",0) ws['A1'] = "Source" ws['B1'] = "mxd" for file in os.listdir(path): if file.endswith(".mxd"): print file rowCount = 2 mxd_path = os.path.join(path,file) mxd = mapping.MapDocument(mxd_path) name = file.split('.')[0] #Sheet names cannot be more than 31 characters name = name[:29] print name #Column names for each mxd ws1 = wb.create_sheet(name,sheetCount) ws1['A1'] = "Layer name" ws1['B1'] = "Layer Type" ws1['C1'] = "Source"
# Challenge - Check for valid directory/folder if os.path.exists(mxd_dir) == False: sys.exit("1, Invalid path specified. Re-run script with valid path.") # Challenge - Set the current workspace for the list function arcpy.env.workspace = mxd_dir # Challenge - Obtain list of mxds in the current folder mxd_list = arcpy.ListFiles("*.mxd") # Challenge - Loop through list, join path and mxd name # Process mxd for name in mxd_list: mxdFile = os.path.join(mxd_dir, name) mxd = MAP.MapDocument(mxdFile) 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")
return def test_layouts(mxd): for pagename in ["8 10 8BB", "8 10 5CD", "8 10 5CD D1", "8 10 5CD D2", ]: print("pagename: %s" % pagename) update_page_layout(mxd, pagename) # ====================================================================== if __name__ == '__main__': try: # Try to run as a python script (from a toolbox in arcmap) mxdname="CURRENT" mapnumber=sys.argv[1] except IndexError: # Run in the debugger mxdname = "C:\\GeoModel\\Clatsop\\Workfolder\\TestMap.mxd" mxd = MAP.MapDocument(mxdname) select_scalebar(mxd, 120) select_scalebar(mxd, 240) select_scalebar(mxd, 1200) select_scalebar(mxd, 2400) select_scalebar(mxd, 4800) select_scalebar(mxd, 24000) test_layouts(mxd) del mxd print("Tests completed.") # That's all
outRas22.save(outPathras + "rasCompPer_crit_5_1.tif") outRas23.save(outPathras + "rasCompPer_crit_6_1.tif") print "Second step of script processing complete" """ --------------------------------------------------------------------------- START THE THIRD PART OF SCRIPT --------------------------------------------------------------------------- """ print "Beginning third step of script processing" # Set up variables env.workspace = "F:\\NFIE_SI_2016\\groupProject\\workspace\\" mapDoc = "F:\\NFIE_SI_2016\\groupProject\\imgCreation.mxd" mxd = mp.MapDocument(mapDoc) rasDir2 = "F:\\NFIE_SI_2016\\groupProject\\postprocessOutput\\rasters\\composites\\" outlyrDir = "F:\\NFIE_SI_2016\\groupProject\\postprocessOutput\\rasters\\layers\\" # Source layers that will be used for symbology reference fldext_srcLyr = mp.Layer(outlyrDir + "fldext_source_stretch.lyr") wd_srcLyr = mp.Layer(outlyrDir + "wd_source_stretch.lyr") fv_srcLyr = mp.Layer(outlyrDir + "fv_source_stretch.lyr") crit_srcLyr = mp.Layer(outlyrDir + "crit_source_stretch.lyr") spatialRef = arcpy.SpatialReference( 3857) # 3857 is code for WGS_1984_Web_Mecator (auxiliary sphere) # Remove all current possible layers in the MXD for df in mp.ListDataFrames(mxd):
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Eric # # Created: 06/04/2018 # Copyright: (c) Eric 2018 # Licence: <your licence> #------------------------------------------------------------------------------- '''In this script, we'll examine how you can use the findAndReplaceWorkspacePaths() method in the MapDocument class to perform global find and replace operations in the layers and tables of a map document. ''' # import the module import arcpy.mapping as mapping # reference map document file mxd = mapping.MapDocument(r"c:\ArcpyBook\Ch3\Crime_BrokenDataLinks.mxd") # fix the source path for each data source in map document # first parameter is old path, second parameter is new path mxd.findAndReplaceWorkspacePaths( r"C:\ArcpyBook\Ch3\Data\OldData\CityOfSanAntonio.gdb", r"C:\ArcpyBook\Data\CityOfSanAntonio.gdb") # save the results to a new mxd file mxd.saveACopy(r"C:\ArcpyBook\Ch3\Crime_DataLinksFixed.mxd") print "New map document created"
import arcpy import arcpy.da as da import arcpy.mapping as harta arcpy.env.workspace = "t:/IE/bd_ro.mdb" arcpy.env.overwriteOutput = True dh = harta.MapDocument("CURRENT") df = harta.ListDataFrames(dh, "Layers")[0] arcpy.AddField_management("judTab", "pondere", "LONG") lval = [rd[0] for rd in da.SearchCursor("judTab", "lungime")] slung = sum(lval) with da.UpdateCursor("judTab", ("lungime", "pondere")) as crs: for rd in crs: rd[1] = int(round(rd[0] / slung * 100)) crs.updateRow(rd) del crs
import arcpy.mapping as mapping, os path = r'C:\EsriTraining' f = open('BrokenDataList.txt', 'w') for root, dirs, files in os.walk(path): for filename in files: basename, extension = os.path.splitext(filename) if extension == ".mxd": fullPath = os.path.join(path, filename) mxd = mapping.MapDocument( r'C:\EsriTraining\PythEveryone\PythonInArcGIS\Crime_DataLinksFixed.mxd' ) f.write("MXD: " + filename + "\n") brknList = mapping.ListBrokenDataSources(mxd) for brknItem in brknList: f.write("\t" + brknItem.name + "\n") f.close() print "script complete!"
import os import sys import arcpy import arcpy.mapping as mapping # get input parameters outDir = arcpy.GetParameterAsText(0) packageMap = arcpy.GetParameter(1) checkBrokenLayers = arcpy.GetParameter(2) # get the map document in which this code is running ("Current" keyword) mxd = mapping.MapDocument('Current') # build a pathname to the output report (text file) reportPath = outDir + '\\' + mxd.title + '.txt' # open the file (will be created if it doesn't exist) reportFile = open(reportPath, 'w') arcpy.AddMessage('Writing report to ' + reportPath) # start writing report text to a string variable reportText = 'Title: ' + mxd.title + '\n' reportText += 'Author: ' + mxd.author + '\n' reportText += 'Description: ' + mxd.description + '\n' reportText += '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' + '\n' # if the user chose to do so, create map package if packageMap: packagePath = outDir + '\\' + mxd.title.replace('.', '_') + '.mpk' if (os.path.exists(packagePath)): arcpy.AddMessage('Map package already exists (' + packagePath + ')') else:
########### [email protected] # # Created: 11/02/2019 # Copyright: (c) Eliška Vlčková 2019 #------------------------------------------------------------------------------- # encoding=utf8 import arcpy, os, sys from arcpy import mapping as map reload(sys) sys.setdefaultencoding('utf8') arcpy.env.workspace = r"C:/gc_work/evl/Data/Belgium/RMS_HD.gdb" mxd = map.MapDocument(r"C:/gc_work/evl/MXDs/RMSHD_atlas.mxd") arcpy.env.overwriteOutput = True ####VARIABLES#### floodmodel = "RMS HD Flood Hazard 2" #user input flood model cityTitle = "Belgium" returnperiod = "100 years" coordinatesystem = "Belge 1972 / Belgian Lambert 72 (EPSG: 31370)" cellsize = "100 x 100 m" cityfield = "CRESTA_DES" try: if arcpy.Exists(arcpy.env.workspace): arcpy.AddMessage("GDb exists") df = map.ListDataFrames(mxd, "Layers")[0]
#------------------------------------------------------------------------------- # Name: Mapping01.py # Purpose: A script to set the following MapDocument properties with specific values: # title,author,credits,summary,description,tags # Use MapDocument("MappingEx.mxd") and run from PyScripter. #Call the save method on MapDocument to save changes to the mxd. # # Author: Emilie Rabeau, Dragos B # # Created: 21-02-2018 # Copyright: (c) mie_r , Dragos_B 2018 # Licence: <your licence> #------------------------------------------------------------------------------- import arcpy.mapping as mapping import os mxd = mapping.MapDocument(r"MappingEx.mxd") mxd.title = "arcpy.mapping module exercises" mxd.author = "Dragos Bologa and Emilie Rabeau" mxd.credits = "David Viljoen made me do it" mxd.summary = "See Description" mxd.description = "This document was used for practicing Python coding with the arcpy.mapping module." mxd.tags = "arcpy.mapping,python,gis4207" mxd.save() del mxd