zoukankan      html  css  js  c++  java
  • 13章代码

    13.1 获得mxd中图层信息

    #coding=utf8
    import arcpy
    
    import os
    import sys
    import math
    
    def getDataFrameinfo(df):
        arcpy.AddMessage("{0:<20s}{1}".format("credits:",df.credits))
        arcpy.AddMessage("{0:<20s}{1}".format("description:",df.description))
        arcpy.AddMessage("{0:<20s}{1}".format("displayUnits:",df.displayUnits))
        arcpy.AddMessage("{0:<20s}{1}".format("elementHeight:",df.elementHeight))
        arcpy.AddMessage("{0:<20s}{1}".format("elementPositionX:",df.elementPositionX))
        arcpy.AddMessage("{0:<20s}{1}".format("elementPositionY: ",df.elementPositionY))
    
        arcpy.AddMessage("{0:<20s}{1}".format("elementWidth: ",df.elementWidth))
        pextent=df.extent
        #范围信息
        arcpy.AddMessage("Extent:
      XMin: {0}, XMax: {1}, YMin: {2}, YMax: {3}".format(
        pextent.XMin, pextent.XMax, pextent.YMin, pextent.YMax))
        arcpy.AddMessage("{0:<20s}{1}".format("geographicTransformations: ",df.geographicTransformations))
        arcpy.AddMessage("{0:<20s}{1}".format("mapUnits: ",df.mapUnits))
        arcpy.AddMessage("{0:<20s}{1}".format("name: ",df.name))
        arcpy.AddMessage("{0:<20s}{1}".format("referenceScale: ",df.referenceScale))
        arcpy.AddMessage("{0:<20s}{1}".format("rotation: ",df.rotation))
        if  hasattr(df,"scale"):
            arcpy.AddMessage("{0:<20s}{1}".format("scale: ",df.scale))
        arcpy.AddMessage("{0:<20s}{1}".format("time: ",df.time))
        arcpy.AddMessage("{0:<20s}{1}".format("type: ",df.type))
    
    
    def getmxdinfo(mxd):
        arcpy.AddMessage("{0:<20s}{1}".format("activeView:       ",mxd.activeView))
        arcpy.AddMessage("{0:<20s}{1}".format("author:       ",mxd.author))
        arcpy.AddMessage("{0:<20s}{1}".format("credits:       ",mxd.credits))
        arcpy.AddMessage("{0:<20s}{1}".format("dateExported:       ",mxd.dateExported))
        arcpy.AddMessage("{0:<20s}{1}".format("datePrinted:       ",mxd.datePrinted))
        arcpy.AddMessage("{0:<20s}{1}".format("dateSaved:       ",mxd.dateSaved))
        arcpy.AddMessage("{0:<20s}{1}".format("description:       ",mxd.description))
        arcpy.AddMessage("{0:<20s}{1}".format("filePath:       ",mxd.filePath))
        arcpy.AddMessage("{0:<20s}{1}".format("hyperlinkBase:       ",mxd.hyperlinkBase))
        arcpy.AddMessage("{0:<20s}{1}".format("isDDPEnabled:       ",mxd.isDDPEnabled))
        arcpy.AddMessage("{0:<20s}{1}".format("relativePaths:       ",mxd.relativePaths))
        arcpy.AddMessage("{0:<20s}{1}".format("summary:       ",mxd.summary))
        pageWidth, pageHeight = mxd.pageSize
        arcpy.AddMessage("{0:<20s}{1}".format("pageWidth:       ",pageWidth))
        arcpy.AddMessage("{0:<20s}{1}".format("pageHeight:       ",pageHeight))
        for df in arcpy.mapping.ListDataFrames(mxd):
            getDataFrameinfo(df)
    
    
    
    def Main():
    
        if mxdfile=="":
            mxd = arcpy.mapping.MapDocument("CURRENT")
        else:
            mxd = arcpy.mapping.MapDocument(mxdfile)
        arcpy.AddMessage(mxdfile)
        getmxdinfo(mxd)
    mxdfile=arcpy.GetParameterAsText(0)
    
    Main()

    13.2 获得mxd信息( 数据框和页面信息)

    #coding=utf8
    import arcpy
    
    import os
    import sys
    import math
    
    def getDataFrameinfo(df):
        arcpy.AddMessage("{0:<20s}{1}".format("credits:",df.credits))
        arcpy.AddMessage("{0:<20s}{1}".format("description:",df.description))
        arcpy.AddMessage("{0:<20s}{1}".format("displayUnits:",df.displayUnits))
        arcpy.AddMessage("{0:<20s}{1}".format("elementHeight:",df.elementHeight))
        arcpy.AddMessage("{0:<20s}{1}".format("elementPositionX:",df.elementPositionX))
        arcpy.AddMessage("{0:<20s}{1}".format("elementPositionY: ",df.elementPositionY))
    
        arcpy.AddMessage("{0:<20s}{1}".format("elementWidth: ",df.elementWidth))
        pextent=df.extent
        #范围信息
        arcpy.AddMessage("Extent:
      XMin: {0}, XMax: {1}, YMin: {2}, YMax: {3}".format(
        pextent.XMin, pextent.XMax, pextent.YMin, pextent.YMax))
        arcpy.AddMessage("{0:<20s}{1}".format("geographicTransformations: ",df.geographicTransformations))
        arcpy.AddMessage("{0:<20s}{1}".format("mapUnits: ",df.mapUnits))
        arcpy.AddMessage("{0:<20s}{1}".format("name: ",df.name))
        arcpy.AddMessage("{0:<20s}{1}".format("referenceScale: ",df.referenceScale))
        arcpy.AddMessage("{0:<20s}{1}".format("rotation: ",df.rotation))
        if hasattr(df,"scale"):
            arcpy.AddMessage("{0:<20s}{1}".format("scale: ",df.scale))
        arcpy.AddMessage("{0:<20s}{1}".format("time: ",df.time))
        arcpy.AddMessage("{0:<20s}{1}".format("type: ",df.type))
    def getGRADUATED_COLORS(lyr):
        arcpy.AddMessage("{0:<20s}{1}".format("valueField:",lyr.symbology.valueField))
        arcpy.AddMessage("{0:<20s}{1}".format("numClasses:",lyr.symbology.numClasses))
    
        BreakValues=lyr.symbology.classBreakValues
        for BreakValue in  BreakValues:
            arcpy.AddMessage("{0:<20s}{1}".format("BreakValue:",BreakValue))
    def getUNIQUE_VALUES(lyr):
        arcpy.AddMessage("{0:<20s}{1}".format("valueField:",lyr.symbology.valueField))
    
        classValues=lyr.symbology.classValues
        for classValue in  classValues:
            arcpy.AddMessage("{0:<20s}{1}".format("classValue:",classValue))
    def getlabel(lyr):
        for lblClass in lyr.labelClasses:
            if lblClass.showClassLabels:
                arcpy.AddMessage("{0:<20s}{1}".format("   Class Name:  ",lblClass.className))
                arcpy.AddMessage("{0:<20s}{1}".format("    Expression: ",lblClass.expression))
                arcpy.AddMessage("{0:<20s}{1}".format("    SQL Query:  ", lblClass.SQLQuery))
    
    #删除一个表的所有字段
    def delAllField(inFeature):
        try:
    
            fieldList = arcpy.ListFields(inFeature)
            for field in fieldList:
                  if not (field.type=="Geometry" or field.type=="OID" or not field.editable):
                      arcpy.DeleteField_management(inFeature,field.name)
        except:
            pass
    
    
    def getmxdinfo(mxd):
        arcpy.AddMessage("{0:<20s}{1}".format("activeView:       ",mxd.activeView))
        arcpy.AddMessage("{0:<20s}{1}".format("author:       ",mxd.author))
        arcpy.AddMessage("{0:<20s}{1}".format("credits:       ",mxd.credits))
        arcpy.AddMessage("{0:<20s}{1}".format("dateExported:       ",mxd.dateExported))
        arcpy.AddMessage("{0:<20s}{1}".format("datePrinted:       ",mxd.datePrinted))
        arcpy.AddMessage("{0:<20s}{1}".format("dateSaved:       ",mxd.dateSaved))
        arcpy.AddMessage("{0:<20s}{1}".format("description:       ",mxd.description))
        arcpy.AddMessage("{0:<20s}{1}".format("filePath:       ",mxd.filePath))
        arcpy.AddMessage("{0:<20s}{1}".format("hyperlinkBase:       ",mxd.hyperlinkBase))
        arcpy.AddMessage("{0:<20s}{1}".format("isDDPEnabled:       ",mxd.isDDPEnabled))
        arcpy.AddMessage("{0:<20s}{1}".format("relativePaths:       ",mxd.relativePaths))
        arcpy.AddMessage("{0:<20s}{1}".format("summary:       ",mxd.summary))
        pageWidth, pageHeight = mxd.pageSize
        arcpy.AddMessage("{0:<20s}{1}".format("pageWidth:       ",pageWidth))
        arcpy.AddMessage("{0:<20s}{1}".format("pageHeight:       ",pageHeight))
        for df in arcpy.mapping.ListDataFrames(mxd):
            #getDataFrameinfo(df)
            arcpy.AddMessage("============{0:<20s}{1}============".format("name: ",df.name))
            for lyr in arcpy.mapping.ListLayers(mxd, "",df):
                arcpy.AddMessage("{0:<20s}{1}".format("name:",lyr.name))
                if not lyr.isBroken:#是否坏了
                    if hasattr(lyr,"brightness"):
                        arcpy.AddMessage("{0:<20s}{1}".format("brightness:",lyr.brightness))
                    if hasattr(lyr,"contrast"):
                        arcpy.AddMessage("{0:<20s}{1}".format("contrast:",lyr.contrast))
                    if hasattr(lyr,"credits"):
                        arcpy.AddMessage("{0:<20s}{1}".format("contrast:",lyr.credits))
                    if hasattr(lyr,"datasetName"):
                        arcpy.AddMessage("{0:<20s}{1}".format("datasetName:",lyr.datasetName))
                    if hasattr(lyr,"dataSource"):
                        arcpy.AddMessage("{0:<20s}{1}".format("dataSource:",lyr.dataSource))
    
                    if hasattr(lyr,"definitionQuery"):
                        arcpy.AddMessage("{0:<20s}{1}".format("definitionQuery:",lyr.definitionQuery))
                    if hasattr(lyr,"description"):
                        arcpy.AddMessage("{0:<20s}{1}".format("description:",lyr.description))
                    if hasattr(lyr,"isFeatureLayer"):
                        arcpy.AddMessage("{0:<20s}{1}".format("isFeatureLayer:",lyr.isFeatureLayer))
                        if lyr.isFeatureLayer:
                            pass
                            #delAllField(lyr)
    
                    if hasattr(lyr,"isGroupLayer"):
                        arcpy.AddMessage("{0:<20s}{1}".format("isGroupLayer:",lyr.isGroupLayer))
                    if hasattr(lyr,"isRasterLayer"):
                        arcpy.AddMessage("{0:<20s}{1}".format("isRasterLayer:",lyr.isRasterLayer))
                    if hasattr(lyr,"longName"):
                        arcpy.AddMessage("{0:<20s}{1}".format("longName:",lyr.longName))
                    if hasattr(lyr,"maxScale"):
                        arcpy.AddMessage("{0:<20s}{1}".format("maxScale:",lyr.maxScale))
    
                    if hasattr(lyr,"minScale"):
                        arcpy.AddMessage("{0:<20s}{1}".format("minScale:",lyr.minScale))
                    if hasattr(lyr,"isRasterLayer"):
                        arcpy.AddMessage("{0:<20s}{1}".format("isRasterLayer:",lyr.isRasterLayer))
                    if hasattr(lyr,"showLabels"):
                        arcpy.AddMessage("{0:<20s}{1}".format("showLabels:",lyr.showLabels))
                        if lyr.showLabels:
                            getlabel(lyr)
    
                    if hasattr(lyr,"transparency"):
                        arcpy.AddMessage("{0:<20s}{1}".format("transparency:",lyr.transparency))
                    if hasattr(lyr,"visible"):
                        arcpy.AddMessage("{0:<20s}{1}".format("visible:",lyr.visible))
                    if hasattr(lyr,"workspacePath"):
                        arcpy.AddMessage("{0:<20s}{1}".format("workspacePath:",lyr.workspacePath))
                    if hasattr(lyr,"symbologyType"):
                        arcpy.AddMessage("{0:<20s}{1}".format("symbologyType:",lyr.symbologyType))
                        if lyr.symbologyType=="GRADUATED_COLORS":
                            getGRADUATED_COLORS(lyr)
                        elif lyr.symbologyType=="UNIQUE_VALUES":
                            getUNIQUE_VALUES(lyr)
    
    def Main():
    
        if mxdfile=="":
            mxd = arcpy.mapping.MapDocument("CURRENT")
        else:
            mxd = arcpy.mapping.MapDocument(mxdfile)
    
    
        arcpy.AddMessage(mxdfile)
        getmxdinfo(mxd)
    mxdfile=arcpy.GetParameterAsText(0)
    
    Main()

    13.4 批量mxd导出图片

    import arcpy
    import os
    import re
    
    from os.path import join, getsize
    
    def getFile(filepath,ext):
        arcpy.env.workspace = filepath
        return arcpy.ListFiles("*"+ext)
    def getmxdfile(workspace,ext):#获得一个文件夹只能扩展名的所有文件
        FileList=[]
        for dirpath, dirnames, filenames in os.walk(workspace):#获得所有的子文件夹
            for filename in filenames:
                #arcpy.AddMessage("filename=="+filename)
    
                if filename.lower().endswith(ext):
                    fullfile=os.path.join(dirpath, filename)
                    arcpy.AddMessage(fullfile)
                    FileList.append(fullfile)
        return FileList
    
    inpath  = arcpy.GetParameterAsText(0)
    outfile = arcpy.GetParameterAsText(1).upper()
    mydpi =   arcpy.GetParameter(2)
    mydir = inpath
    a=getmxdfile(mydir,".mxd")
    
    for b in a:
        arcpy.AddMessage(b)
        mxd = arcpy.mapping.MapDocument(b)
        #arcpy.AddMessage("mxd="+str(mxd))
        jpg=b.replace('.mxd',outfile)
        arcpy.AddMessage("pic:"+jpg)
        try:
              if outfile==".JPG":
                arcpy.mapping.ExportToJPEG(mxd, jpg,resolution=mydpi)
              elif outfile==".TIF":
                arcpy.mapping.ExportToTIFF(mxd, jpg,resolution=mydpi)
              elif outfile==".PDF":
                arcpy.mapping.ExportToPDF(mxd, jpg,resolution=mydpi,convert_markers=True)
              elif outfile==".PNG":
                arcpy.mapping.ExportToPNG(mxd, jpg,resolution=mydpi)
              elif outfile==".EMF":
                arcpy.mapping.ExportToEMF(mxd, jpg,resolution=mydpi)
              else:
                arcpy.mapping.ExportToPDF(mxd, jpg,resolution=mydpi)
        except Exception as e:
              print e.message
              arcpy.AddError(e.message)
        del mxd

    13.5 地图窗口转到XY

    #coding=utf8
    
    import arcpy
    import os
    import types
    import string
    
    def getCount(inFeature):
        result = arcpy.GetCount_management(inFeature)
        count= int(result.getOutput(0))
        return count
    def getwhereCount(inFeature,wherestr):
        my_temp="my_temp" #临时数据
    
        arcpy.MakeFeatureLayer_management(inFeature,my_temp,wherestr)
        return getCount(my_temp)
    def FieldExists(TableName,FieldName):
        desc = arcpy.Describe(TableName)
        for field in desc.fields:
            if field.Name.upper() ==FieldName:
                return True
                break
        return False
    
    def getOIDField(jfb_Select):
        desc = arcpy.Describe(jfb_Select)
        OIDField=desc.OIDFieldName
        return OIDField
    
    def initProgress(hint,num):
        arcpy.SetProgressor("step", u"正在"+hint,0,num,1)
    def step():
        arcpy.SetProgressorLabel(u"正在进行....")
        arcpy.SetProgressorPosition()
    def freeProgress():
        arcpy.ResetProgressor()
    def is_number(str):
        try:
            # 因为使用float有一个例外是'NaN'
            if str=='NaN':
                return False
            float(str)
            return True
        except ValueError:
            return False
    
    #必须是u类型==================u====================
    def dmstod(dms):
        #arcpy.AddMessage("================================="+dms+"==============================")
        try:
            p = dms.find('°')
            if p<0:
                return str(dms)
            #arcpy.AddMessage("p="+str(p))
            d=string.atof(dms[0:p].strip())
            #arcpy.AddMessage("d="+str(d))
            p1=dms.find('')
            #arcpy.AddMessage("p1="+str(p1))
            if p1<0:
                 p1=dms.find("'")
    
            f=0 #
            if p1>0:
                f=string.atof(dms[p+1:p1].strip())
            else:
                p1=p
            #arcpy.AddMessage("f="+str(f))
    
            p2=dms.find('')
            if p2<0:
                 p2=dms.find('"')
            #arcpy.AddMessage("p2="+str(p2))
    
            s=0 #
            if p2>0:
                s=string.atof(dms[p1+1:p2].strip())
            #arcpy.AddMessage("s="+str(s))
    
            return d+f/60+s/3600
        except ValueError:
            return None
    #获得一个点的投影坐标系
    def getpjxy(gx,gy,sr,GCSsr):
        point = arcpy.Point()
        point.X = gx
        point.Y = gy
    
        pointGeometry = arcpy.PointGeometry(point,GCSsr)
        newpointgeo=  pointGeometry.projectAs(sr)
        p1=newpointgeo.firstPoint
        return p1.X,p1.Y
    def main():
        isdms=False
        if is_number(x):
            xd= float(x)
        else:
            isdms=True
            xd=dmstod(u""+x)
            if xd==None:
                arcpy.AddError(u"输入x={0}不是有效的数字".format(x))
                return
            if xd>180 or xd<-180:
                arcpy.AddError(u"输入x={0}不是有效的数字".format(x))
                return
    
    
        if is_number(y):
            yd= float(y)
        else:
            isdms=True
            yd=dmstod(u""+y)
            if yd==None:
                arcpy.AddError(u"输入y={0}不是有效的数字".format(y))
                return
            if yd>90 or y<-90:
                arcpy.AddError(u"输入y={0}不是有效的数字".format(y))
                return
    
        mxd = arcpy.mapping.MapDocument("CURRENT")
        df=mxd.activeDataFrame
        if df.scale!=scale:
            df.scale=scale
            arcpy.RefreshActiveView()
    
        sr=df.spatialReference
        if sr.name == "Unknown":
            arcpy.AddError("数据框请"+"定义坐标系,没有定义坐标!")
            return
    
        pextent=df.extent
        h=pextent.height
        w=pextent.width
        GCSsr=sr.GCS
        if GCSsr.factoryCode!=sr.factoryCode: #不是地理坐标系
            if isdms==True:#是度分秒
                xd,yd=getpjxy(xd,yd,sr,GCSsr)
            elif xd>-180 and xd<180 and yd>-90 and yd<90:
                xd,yd=getpjxy(xd,yd,sr,GCSsr)
       #定义范围
        pextent.XMin, pextent.YMin = xd-w/2, yd-h/2
        pextent.XMax, pextent.YMax =  xd+w/2, yd+h/2
        df.extent = pextent
    
        arcpy.RefreshActiveView()
    
    x = arcpy.GetParameterAsText(0) #x
    y= arcpy.GetParameterAsText(1) #y
    scale=arcpy.GetParameter(2)
    
    main()

    13.6  固定比例尺打印

    #coding=utf8
    import arcpy
    
    import os
    import sys
    import math
    
    def getmxdinfo(mxd):
        pageWidth, pageHeight = mxd.pageSize
        aDataFrame=mxd.activeDataFrame
        aDataFrame.elementPositionX=0
        aDataFrame.elementPositionY=0
        aDataFrame.elementHeight=pageHeight
        aDataFrame.elementWidth=pageWidth
        lyr = arcpy.mapping.ListLayers(mxd, "dltb", aDataFrame)[0]
        desc = arcpy.Describe(lyr)
        aDataFrame.panToExtent(desc.extent)
        aDataFrame.scale=10000  #固定1:10000比例尺
        arcpy.RefreshActiveView()
        mxd.saveACopy(outfile)
    
    def Main():
    
        if mxdfile=="":
            mxd = arcpy.mapping.MapDocument("CURRENT")
        else:
            mxd = arcpy.mapping.MapDocument(mxdfile)
        arcpy.AddMessage(mxdfile)
    
        getmxdinfo(mxd)
    mxdfile=arcpy.GetParameterAsText(0)
    outfile=arcpy.GetParameterAsText(1)
    
    Main()

    13.7         mxd文档相对路径和无效数据检查

    import arcpy
    import os
    import re
    
    from os.path import join, getsize
    def initProgress(hint,num):
        arcpy.SetProgressor("step", u"正在"+hint,0,num,1)
    def step():
        arcpy.SetProgressorLabel(u"正在进行....")
        arcpy.SetProgressorPosition()
    def freeProgress():
        arcpy.ResetProgressor()
    def getmxdfile(workspace,ext):
        FileList=[]
        for dirpath, dirnames, filenames in os.walk(workspace):
            for filename in filenames:
                #arcpy.AddMessage("filename=="+filename)
    
                if filename.lower().endswith(ext.lower()):
                    fullfile=os.path.join(dirpath, filename)
                    arcpy.AddMessage(fullfile)
                    FileList.append(fullfile)
        return FileList
    
    inpath  = arcpy.GetParameterAsText(0)
    setrel  = arcpy.GetParameter(1) #相对路径设置
    mydir = inpath
    a= getmxdfile(mydir,".mxd")
    num=len(a)
    
    initProgress(u"检查",num)
    for b in a:
          step()
          arcpy.AddMessage(b)
          try:
              mxd = arcpy.mapping.MapDocument(b)
              if mxd is None:
                  arcpy.AddMessage(u"mxd="+b+u",版本太高,无法打开")
                  continue
              if not mxd.relativePaths:#不是相对路径
                arcpy.AddMessage(u"mxd="+b+u",不是相对路径")
                if setrel:#保存相对路径
                    mxd.save()
              for df in arcpy.mapping.ListDataFrames(mxd):
                    for lyr in arcpy.mapping.ListLayers(mxd,"",df):
                          if hasattr(lyr, 'dataSource'):
                                dataSource=lyr.dataSource
                                if lyr.isBroken:#是否损坏
                                    arcpy.AddMessage(u"图层"+lyr.name+",坏了")
                                    
                                if not arcpy.Exists(dataSource):#是否存在
                                      arcpy.AddMessage(u"图层"+lyr.name+u"对应的数据源:'"+dataSource+u"'无效")
    
                                print lyr.name
              if mxd:
                    del mxd
          except Exception as e:
              print e.message
              # If using this code within a script tool, AddError can be used to return messages
              #   back to a script tool.  If not, AddError will have no effect.
              arcpy.AddError(e.message)
    freeProgress()
  • 相关阅读:
    BZOJ-1016 最小生成树计数
    BZOJ-1003 物流运输
    BZOJ-1009 GT考试
    【NOIP2014】伤感·伤感·伤感
    BZOJ-1033 杀蚂蚁
    NOIP一系列模拟赛小结
    2014·NOIP 新的历程,新的开始
    35. Search Insert Position
    29. Divide Two Integers
    28. Implement strStr()
  • 原文地址:https://www.cnblogs.com/gisoracle/p/13556188.html
Copyright © 2011-2022 走看看