ArcGIS Pro python实用工具

视角保存与恢复

import arcpy
import json

def save_view_to_file(file_path):
    """保存当前2D地图视图范围到JSON文件"""
    aprx = arcpy.mp.ArcGISProject("CURRENT")
    map_view = aprx.activeView
    
    # 获取当前地图范围
    current_extent = map_view.camera.getExtent()
    
    # 保存范围信息
    view_data = {
        'xmin': current_extent.XMin,
        'ymin': current_extent.YMin,
        'xmax': current_extent.XMax,
        'ymax': current_extent.YMax,
        'spatial_ref': current_extent.spatialReference.factoryCode
    }
    
    # 写入JSON文件
    with open(file_path, 'w') as f:
        json.dump(view_data, f)
    print(f"地图范围已保存至: {file_path}")

def restore_view_from_file(file_path):
    """从JSON文件恢复2D地图范围"""
    try:
        with open(file_path, 'r') as f:
            view_data = json.load(f)
    except:
        print("错误:无法读取视图文件")
        return

    aprx = arcpy.mp.ArcGISProject("CURRENT")
    map_view = aprx.activeView
    
    # 创建新的范围对象
    sr = arcpy.SpatialReference(view_data['spatial_ref'])
    new_extent = arcpy.Extent(
        view_data['xmin'], 
        view_data['ymin'],
        view_data['xmax'], 
        view_data['ymax'],
        spatial_reference=sr
    )
    
    # 应用保存的范围
    map_view.camera.setExtent(new_extent)
    map_view.update()  # 使用 update() 而不是 updateContents()
    print("地图范围已恢复")

# 使用示例
save_file = r"G:\saved_view.json"  # 替换为你的实际路径

# 保存当前视图
save_view_to_file(save_file)

# 进行其他地图操作后...

# 恢复保存的视图
restore_view_from_file(save_file)
posted @ 2025-07-21 10:51  MARSHBAN  阅读(9)  评论(0)    收藏  举报