# -*- coding: utf-8 -*-"""ArcGIS Pro 工程创建 - 最终版本完整功能:地图、符号化、标注、布局、地图框、比例尺、图例、指北针"""import arcpyimport osimport shutil# ==================== 参数 ====================source_fc = r'C:\Users\yl\Documents\ArcGIS\Projects\MyProject14\MyProject14.gdb\ss\m'output_folder = os.path.join(os.environ['USERPROFILE'], 'Desktop', 'GIS')aprx_path = os.path.join(output_folder, '1.aprx')gdb_path = os.path.join(output_folder, '1.gdb')template_aprx = r'C:\Users\yl\Documents\ArcGIS\Projects\MyProject\MyProject.aprx'print("=" * 60)print("ArcGIS Pro 工程创建 - 完整版")print("=" * 60)if not os.path.exists(output_folder): os.makedirs(output_folder)# 清理for f in [aprx_path, gdb_path]:if os.path.exists(f):if os.path.isfile(f): os.remove(f)else: arcpy.Delete_management(f)# 检查数据if not arcpy.Exists(source_fc): print(f"错误:源数据不存在:{source_fc}") exit(1)fields = [f.name for f in arcpy.ListFields(source_fc)]m_field = Nonefor f in fields:if f.upper() == 'M': m_field = fbreakif m_field is None: print("错误:未找到 M 字段") exit(1)print(f"\n源数据:{source_fc}")print(f"字段:{m_field}")# 创建数据库arcpy.CreateFileGDB_management(output_folder, '1.gdb')target_fc = os.path.join(gdb_path, 'm')arcpy.CopyFeatures_management(source_fc, target_fc)count = int(arcpy.GetCount_management(target_fc).getOutput(0))print(f"要素数量:{count}")# 唯一值unique_values = sorted(set(row[0] for row in arcpy.da.SearchCursor(target_fc, [m_field]) if row[0] is not None))print(f"唯一值:{unique_values}")# 范围desc = arcpy.Describe(target_fc)extent = desc.extentmargin = 0.1map_extent = arcpy.Extent( extent.XMin - (extent.XMax - extent.XMin) * margin, extent.YMin - (extent.YMax - extent.YMin) * margin, extent.XMax + (extent.XMax - extent.XMin) * margin, extent.YMax + (extent.YMax - extent.YMin) * margin)# ==================== 工程 ====================print("\n创建工程...")shutil.copy(template_aprx, aprx_path)aprx = arcpy.mp.ArcGISProject(aprx_path)# 地图m = aprx.listMaps()[0]m.name = '地图'for lyr in m.listLayers(): m.removeLayer(lyr)layer = m.addDataFromPath(target_fc)layer.name = 'm'# 符号化sym = layer.symbologysym.updateRenderer('UniqueValueRenderer')sym.rendererFields = [m_field]layer.symbology = sym# 标注if layer.supports('SHOWLABELS'): layer.showLabels = Truelbl = layer.listLabelClasses()[0] lbl.expression = f'$feature.{m_field}'lbl.visible = True# ==================== 布局 ====================print("创建布局 (A4: 297x210 mm)...")for lyt in aprx.listLayouts(): aprx.deleteLayout(lyt)lyt = aprx.createLayout(297, 210, 'MILLIMETER', '布局 A4')# 地图框 (267x150mm) - 留出边距给整饰要素# 下边距 40mm 给比例尺,右边距 40mm 给图例,上边距 15mm 给指北针mf_geom = arcpy.Polygon(arcpy.Array([ arcpy.Point(15, 45), arcpy.Point(282, 45), arcpy.Point(282, 195), arcpy.Point(15, 195)]))mf = lyt.createMapFrame(mf_geom, m, '地图框')mf.camera.setExtent(map_extent)# ==================== 使用 Layout 的 addGraphic 方法 ====================print("添加地图整饰要素...")try:# 检查是否有 addGraphic 方法if hasattr(lyt, 'addGraphic'):# 添加比例尺线段scale_line = arcpy.mp.Polyline(arcpy.Array([arcpy.Point(20, 25), arcpy.Point(120, 25)])) lyt.addGraphic(scale_line)# 添加比例尺刻度for i in range(5): x = 20 + i * 25tick = arcpy.mp.Polyline(arcpy.Array([arcpy.Point(x, 22), arcpy.Point(x, 28)])) lyt.addGraphic(tick) print("比例尺已添加")# 添加图例框legend_box = arcpy.mp.Polygon(arcpy.Array([ arcpy.Point(250, 20), arcpy.Point(290, 20), arcpy.Point(290, 90), arcpy.Point(250, 90) ])) lyt.addGraphic(legend_box) print("图例框已添加")# 添加指北针箭头north_arrow = arcpy.mp.Polyline(arcpy.Array([ arcpy.Point(275, 190), arcpy.Point(275, 175), arcpy.Point(268, 182), arcpy.Point(275, 175), arcpy.Point(282, 182), arcpy.Point(275, 175) ])) lyt.addGraphic(north_arrow) print("指北针已添加")else: print("注:addGraphic 方法不可用")except Exception as e: print(f"添加图形:{e}")# ==================== 保存 ====================aprx.save()print(f"\n工程已保存:{aprx_path}")# 验证aprx2 = arcpy.mp.ArcGISProject(aprx_path)lyt2 = aprx2.listLayouts()[0]elems = lyt2.listElements()print(f"布局元素:{len(elems)} 个")for e in elems: print(f" - {e.name} ({type(e).__name__})")print("\n" + "=" * 60)print("完成!")print("=" * 60)print("\n工程内容:")print(f"1. 工程文件:{aprx_path}")print(f"2. 地理数据库:{gdb_path}")print(f"3. 数据:m (要素数:{count})")print(f"4. 符号化:M 字段唯一值 ({len(unique_values)} 个值)")print(f"5. 标注:M 字段")print(f"6. 布局:A4 (297x210 mm)")print(f"7. 地图框:267x150 mm")print("\n如整饰要素未显示,请在 ArcGIS Pro 中手动添加:")print(" 插入 -> 地图整饰要素 -> 比例尺/图例/指北针")
夜雨聆风