• 利用mxd文档和切片文件发布地图切片服务


    使用arcpy脚本发布地图切片服务会比人工发布更加方便快捷,步骤如下(1)发布动态服务;(2)创建地图服务缓存;(3)创建切片文件并生成切片。

    import sys, os, time, io, string
    import arcpy
    import xml.dom.minidom as DOM
    import datetime
    
    #sys.setdefaultencoding('utf-8')#本意是支持中文字符,结果导致print无输出
    
    #发布服务本地缓存路径
    wrkspc = r"C:cache"
    #GIS服务器.ags连接文件,注意无空格、特殊字符、中文等
    conn = r"C:UsersAdministratorAppDataRoamingESRIDesktop10.2ArcCatalogxxxxx_publisher.ags"
    #发布服务文件夹
    foldername = "TEST"
    #远程GIS服务器上的服务缓存目录
    cachepath = r"D:arcgisserverdirectoriesarcgiscache"
    #切片方案文件
    tilingscheme = r"D:CutConfig.xml"
    #切片方案文件对应的切片比例级数
    numscales = "6"
    
    #发布Arcgis动态服务,返回服务路径
    #mxdpath - mxd文件路径
    #agspath - GIS服务器.ags连接文件路径
    #serverfolder - 发布服务文件夹
    #summary - 服务描述,仅支持英文
    #tags - 服务标签,仅支持英文
    def PublishService(mxdpath, agspath, serverfolder, summary, tags):
        print("begin PublishService")
        new_mxd = arcpy.mapping.MapDocument(mxdpath)
        dirname = os.path.dirname(mxdpath)
        mxdname = os.path.basename(mxdpath)
        dotindex = mxdname.index('.')
        servicename = mxdname[0:dotindex]
        sddraft = wrkspc + '\temp\' + servicename + '.sddraft'
        sd = wrkspc + '\' + servicename + '.sd'
        if os.path.exists(sd):
            os.remove(sd)
            
        #创建服务定义草稿draft文件
        arcpy.mapping.CreateMapSDDraft(new_mxd, sddraft, servicename, 'ARCGIS_SERVER',
                                                  agspath, False, foldername, summary, tags)
    
        #编辑draft文件
        doc = DOM.parse(sddraft)
        #修改参数minScale and maxScale,禁用缓存
        configProps = doc.getElementsByTagName('ConfigurationProperties')[0]
        propArray = configProps.firstChild
        propSets = propArray.childNodes
        for propSet in propSets:
            keyValues = propSet.childNodes
            for keyValue in keyValues:
                if keyValue.tagName == 'Key':
                    if keyValue.firstChild.data == 'isCached':
                        keyValue.nextSibling.firstChild.data = 'false'#'true'
                    elif keyValue.firstChild.data == 'minScale':
                        keyValue.nextSibling.firstChild.data = '3600000'
                    elif keyValue.firstChild.data == 'maxScale':
                        keyValue.nextSibling.firstChild.data = '1000'
        #禁用KmlServer
        typeNames = doc.getElementsByTagName('TypeName')
        for typeName in typeNames:
            if typeName.firstChild.data == 'KmlServer':
                extension = typeName.parentNode
                for extElement in extension.childNodes:
                    if extElement.tagName == 'Enabled':
                        extElement.firstChild.data = 'false'
                break
        #修改sddraft文件路径
        outXml = wrkspc + '\' + servicename + '.sddraft'
        draftPaths = doc.getElementsByTagName('OnPremisePath')
        for draftPath in draftPaths:
            if draftPath.firstChild.data == sddraft:
                draftPath.firstChild.data = outXml
        #保存draft
        with open(outXml, 'w') as fh:
            doc.writexml(fh, encoding='UTF-8')
        del doc
        sddraft = outXml
    
        #分析sddraft
        analysis = arcpy.mapping.AnalyzeForSD(sddraft)
        if analysis['errors'] == {}:
            arcpy.StageService_server(sddraft, sd)
            arcpy.UploadServiceDefinition_server(sd, agspath)
            return agspath.replace('.ags', '\' + serverfolder + '\' + servicename + '.MapServer')
        else:
            anaErrors = analysis['errors']
            for((message,code),layerlist)in anaErrors.iteritems():
                print("error " + str(code) + ": " + message)
            return ""
    
    
    #创建地图服务缓存
    #inputService - PublishService返回的服务路径
    #serverCachePath - 服务器缓存目录路径
    #predefinedTilingScheme - 切片方案文件
    #numOfScales - 要在缓存中创建的比例级数(对应切片方案文件)
    def CreateCache(inputService, serverCachePath, predefinedTilingScheme, numOfScales):
        print("begin CreateCache")
        #List of input variables for map service properties
        tilingSchemeType = "PREDEFINED"
        scalesType = ""
        dotsPerInch = "96"
        tileSize = "256 x 256"
        predefinedTilingScheme = tilingscheme
        tileOrigin = ""
        scales = ""
        cacheTileFormat = "PNG"
        tileCompressionQuality = "0"
        storageFormat = "COMPACT"
        try:
            starttime = time.clock()
            result = arcpy.CreateMapServerCache_server(inputService, serverCachePath,
                                                       tilingSchemeType, scalesType,
                                                       numOfScales, dotsPerInch,
                                                       tileSize, predefinedTilingScheme,
                                                       tileOrigin, scales,
                                                       cacheTileFormat, tileCompressionQuality,
                                                       storageFormat)
            while result.status < 4:
                time.sleep(0.2)
            resultValue = result.getMessages()
            #print("message: " + str(resultValue))#此处总是报错调到except
        except Exception, e:
            #打印出错误号和信息
            tb = sys.exc_info()[2]
            print("error line: " + str(tb.tb_lineno))
            print("error: " + e.message)
            return False
        return True
    
    
    #生成切片
    #inputService - PublishService返回的服务路径
    def CreateTiles(inputService):
        print("begin CreateTiles")
        scales = ""
        numOfCachingServiceInstances = 2
        updateMode = "RECREATE_ALL_TILES"
        areaOfInterest = ""
        waitForJobCompletion = "WAIT"
        updateExtents = ""
        try:
            result = arcpy.ManageMapServerCacheTiles_server(inputService, scales,
                                                            updateMode, numOfCachingServiceInstances,
                                                            areaOfInterest, updateExtents,
                                                            waitForJobCompletion)
            while result.status < 4:
                time.sleep(0.2)
            resultValue = result.getMessages()
            #print("message: " + str(resultValue))#此处总是报错调到except
        except Exception, e:
            #打印出错误号和信息
            tb = sys.exc_info()[2]
            print("error line: " + str(tb.tb_lineno))
            print("error: " + e.message)
            return False
        return True
    
    
    #mxd文件发布为arcserver切片服务
    #mxdpath - mxd文件路径
    #summary - 服务摘要(仅支持英文)
    #tags - 服务标签(仅支持英文)
    def PublishMxdServer(mxdpath, summary, tags):
        start = datetime.datetime.now()
        print("Publish " + mxdpath)
        resService = PublishService(mxdpath, conn, foldername, summary, tags)
        #服务路径 = .ags全路径去除后缀 + 服务发布文件夹 + 服务名 + .MapServer
        #resService = r"C:UsersAdministratorAppDataRoamingESRIDesktop10.2ArcCatalogxxxxx_publisherTESTserver_name.MapServer"
        if resService == "":
            sys.exit(0)
        if CreateCache(resService, cachepath, tilingscheme, numscales) == False:
            sys.exit(0)
        if CreateTiles(resService) == False:
            sys.exit(0)
        end = datetime.datetime.now()
        print("End publish : {:.4f}s".format((end-start).seconds))
        print("--")
    
    
    #===============================================================================
    # *****程序运行入口*****
    #===============================================================================
    
    #PublishMxdServer(r"D:mxdxxx.mxd", "", "")
    mxddir = r"D:mxd"
    for f in os.listdir(mxddir):
        path = mxddir + "\" + f
        if os.path.isfile(path):
            PublishMxdServer(path, "", "")


    附上一个切片方案文件;

    <?xml version="1.0" encoding="utf-8" ?>
    <CacheInfo xsi:type='typens:CacheInfo' 
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
    xmlns:xs='http://www.w3.org/2001/XMLSchema' 
    xmlns:typens='http://www.esri.com/schemas/ArcGIS/10.6'>
        <TileCacheInfo xsi:type='typens:TileCacheInfo'>
            <SpatialReference xsi:type='typens:ProjectedCoordinateSystem'>
                <WKT>PROJCS[&quot;CGCS2000_3_Degree_GK_Zone_39&quot;,GEOGCS[&quot;GCS_China_Geodetic_Coordinate_System_2000&quot;,DATUM[&quot;D_China_2000&quot;,SPHEROID[&quot;CGCS2000&quot;,6378137.0,298.257222101]],PRIMEM[&quot;Greenwich&quot;,0.0],UNIT[&quot;Degree&quot;,0.0174532925199433]],PROJECTION[&quot;Gauss_Kruger&quot;],PARAMETER[&quot;False_Easting&quot;,39500000.0],PARAMETER[&quot;False_Northing&quot;,0.0],PARAMETER[&quot;Central_Meridian&quot;,117.0],PARAMETER[&quot;Scale_Factor&quot;,1.0],PARAMETER[&quot;Latitude_Of_Origin&quot;,0.0],UNIT[&quot;Meter&quot;,1.0],AUTHORITY[&quot;EPSG&quot;,4527]]</WKT>
                <XOrigin>33876800</XOrigin>
                <YOrigin>-10002100</YOrigin>
                <XYScale>450265407.00157917</XYScale>
                <ZOrigin>0</ZOrigin>
                <ZScale>1</ZScale>
                <MOrigin>-100000</MOrigin>
                <MScale>10000</MScale>
                <XYTolerance>0.001</XYTolerance>
                <ZTolerance>2</ZTolerance>
                <MTolerance>0.001</MTolerance>
                <HighPrecision>true</HighPrecision>
                <WKID>4527</WKID>
                <LatestWKID>4527</LatestWKID>
            </SpatialReference>
            <TileOrigin xsi:type='typens:PointN'>
                <X>33876800</X><Y>10002100</Y>
            </TileOrigin>
            <TileCols>256</TileCols>
            <TileRows>256</TileRows>
            <DPI>96</DPI>
            <LODInfos xsi:type='typens:ArrayOfLODInfo'>
                <LODInfo xsi:type='typens:LODInfo'>
                    <LevelID>0</LevelID><Scale>125000</Scale><Resolution>33.072982812632297</Resolution>
                </LODInfo>
                <LODInfo xsi:type='typens:LODInfo'>
                    <LevelID>1</LevelID><Scale>64000</Scale><Resolution>16.933367200067735</Resolution>
                </LODInfo>
                <LODInfo xsi:type='typens:LODInfo'>
                    <LevelID>2</LevelID><Scale>32000</Scale><Resolution>8.4666836000338677</Resolution>
                </LODInfo>
                <LODInfo xsi:type='typens:LODInfo'>
                    <LevelID>3</LevelID><Scale>16000</Scale><Resolution>4.2333418000169338</Resolution>
                </LODInfo>
                <LODInfo xsi:type='typens:LODInfo'>
                    <LevelID>4</LevelID><Scale>8000</Scale><Resolution>2.1166709000084669</Resolution>
                </LODInfo>
                <LODInfo xsi:type='typens:LODInfo'>
                    <LevelID>5</LevelID><Scale>4000</Scale><Resolution>1.0583354500042335</Resolution>
                </LODInfo>
            </LODInfos>
            <PreciseDPI>96</PreciseDPI>
        </TileCacheInfo>
        <TileImageInfo xsi:type='typens:TileImageInfo'>
            <CacheTileFormat>PNG</CacheTileFormat>
            <CompressionQuality>0</CompressionQuality>
            <Antialiasing>false</Antialiasing>
            <BandCount>1</BandCount>
            <LERCError>0</LERCError>
        </TileImageInfo>
        <CacheStorageInfo xsi:type='typens:CacheStorageInfo'>
            <!--StorageFormat可以修改为esriMapCacheStorageModeCompact,V2版本不兼容10.2.2的ArcGIS-->
            <StorageFormat>esriMapCacheStorageModeCompactV2</StorageFormat>
            <PacketSize>128</PacketSize>
        </CacheStorageInfo>
    </CacheInfo>
  • 相关阅读:
    task-clph
    遍历数组的方式
    iOS事件处理之七种手势
    quatz2d使用注意点
    iOS 细碎知识整理
    九宫格算法图示
    mac10.12的Cocopods安装使用
    静态库冲突的解决办法:duplicate symbol
    ceshi
    xmpp4-总览
  • 原文地址:https://www.cnblogs.com/publiter/p/15076206.html
Copyright © 2020-2023  润新知