出圖是項目里常見的任務,有的項目甚至會要上百張圖片,所以批量出土工具很有必要。arcpy.mapping就是ArcGIS里的出圖模塊,能快速完成一個出圖工具。
arcpy.mapping模塊里常用的類有MapDocument、DataFrame、Layer、DataDrivenPages和TextElement。
MapDocument類是地圖文檔(.mxd文件)對應的類。初始化參數是一個字符串,一般是.mxd文件的路徑:
mxd=arcpy.mapping.MapDocument(r"F:/GeoData/ChinaArea/ChinaVector.mxd")
DataFrame類用于操作地圖內的Data Frame(即下圖的Layers),能夠控制地圖的范圍、比例尺等。用arcpy.mapping.ListDataFrames(map_document, {wildcard})函數獲取。
df= arcpy.mapping.ListDataFrames(mxd)[0]
Layer類用于操作具體的圖層。能夠控制圖斑的樣式、可見性等。可以用.lyr文件的路徑初始化,也可以通過arcpy.mapping.ListLayers(map_document_or_layer, {wildcard}, {data_frame})函數獲取。
lyr1=arcpy.mapping.Layer(r" F:/GeoData/ChinaArea/Province.lyr")df.addLayer(lyr1)lyr2=arcpy.mapping.ListLayer(mxd,"",df)[0]
DataDrivenPages類需要配合ArcMap中的Data Driven Pages工具使用。用于一個矢量文件內的全部或部分圖斑每個出一張圖的情況。
TextElement類用于操作地圖上的文字,比如圖名、頁數。通過arcpy.mapping.ListLayoutElements (map_document, {element_type}, {wildcard})函數獲取。
txtElm=arcpy.mapping.ListLayoutElements(mxd,"TEXT_ELEMENT")[0]
常見的出圖模式有兩種:一個矢量文件里每個圖斑出一張圖,一個文件夾下每個矢量文件出一張圖。
每個圖斑出一張圖:
這種情況有Data Driven Pages工具配合最好。打開ArcMap的Customize->Toolbars->Data Driven Pages,設置好圖層、名稱字段、排序字段、顯示范圍和比例尺,保存地圖。
# coding:utf-8import arcpy mxd=arcpy.mapping.MapDocument(r"F:/GeoData/ChinaArea/ChinaVector.mxd")for pageNum in range(1,mxd.dataDrivenPages.pageCount): mxd.dataDrivenPages.currentPageID=pageNum mapName=mxd.dataDrivenPages.pageRow.getValue(mxd.dataDrivenPages.pageNameField.name) print mapName arcpy.mapping.ExportToPNG(mxd,r"F:/GeoData/ChinaArea/Province//"+mapName+".png")print 'ok'
一個文件夾下的每個矢量文件出一張圖:
# coding:utf-8import arcpyimport os def GetShpfiles(shpdir):     shpfiles=[]     allfiles=os.listdir(shpdir)     for file in allfiles:          if os.path.isfile(file):              if file.endswith('.shp'):                   shpfiles.append(file)          else:              shpfiles.extend(GetShpfiles(file))     return shpfiles allshps=GetShpfiles(r"F:/GeoData/ChinaArea/Province")mxd=arcpy.mapping.MapDocument(r"F:/GeoData/ChinaArea/ChinaVector.mxd")lyr=arcpy.mapping.ListLayer(mxd)[0]for shp in allshps:     paths=os.path.split(shp)     print paths[1]     lyr.replaceDataSource(paths[0],"SHAPEFILE_WORKSPACE",paths[1])     arcpy.mapping.ExportToPNG(mxd,r"F:/GeoData/ChinaArea/Province//"+paths[1]+".png")print 'ok'            
新聞熱點
疑難解答