def plot_with_arcpy(init_time, replace_workspace_dir,origin_workspace_dir, images_dir, mxd_path, resolution=100):
    mxd = mp.MapDocument(mxd_path)
    
    # 修改预报时效
    txts = mp.ListLayoutElements(mxd, "TEXT_ELEMENT")
    init_time_datetime = datetime.datetime.strptime(init_time, '%y%m%d%H')
    for valid_h, i in zip(range(0, 132, 12), range(23, 12, -1)):
        beg = (init_time_datetime + datetime.timedelta(hours=valid_h)).strftime('%d%H')
        end = (init_time_datetime + datetime.timedelta(hours=valid_h + 12)).strftime('%d%H')
        txts[i].text = beg + '-' + end

    # 替换数据源
    mxd.replaceWorkspaces(origin_workspace_dir, "RASTER_WORKSPACE", replace_workspace_dir, "RASTER_WORKSPACE", False)
    # 处理缺失数据
    broken_lyrs = mp.ListBrokenDataSources(mxd)
    for broken_lyr in broken_lyrs:
        # 让缺失数据图层及与其同在一个dataframe里其他的图层不显示
        broken_df = mp.ListDataFrames(mxd, broken_lyr.name)
        if len(broken_dfs) > 0:
            lyrs_in_broken_df = mp.ListLayers(mxd, "", broken_df[0])
            for lyr in lyrs_in_broken_df:
                lyr.visible = False
                
    #mxd.save() 不要保存
    mp.ExportToJPEG(mxd, os.path.join(images_dir, init_time), resolution=resolution)
Beispiel #2
0
def import_anno(mxdname, geodatabase):
    """ Import annotation coverages into annotation feature classes. """

    workspace = os.path.join(geodatabase, "annotation_fd")

    # too late, can't do this here. dang arcgis limitation
    #    infc = os.path.join(workspace, all_taxlot_anno)
    #    whereclause = "TextString='99-99' OR TextString='ROAD' OR TextString='WATER' OR TextString='RAIL' OR TextString LIKE 'GAP%'"
    #    dropfeatures(infc, whereclause)
    #    return

    layers = [
        ("tmpbearingan", "bearing_anno"),
        ("tmpseemapan", "seemap_anno"),
        ("tmptaxlotan", "taxlot_anno"),
        ("tmptaxcodan", "taxcode_anno"),
        ("tmptaxmapan", "taxmap_anno"),
    ]
    logging.info("import_anno(%s, %s)" % (mxdname, geodatabase))
    mxd = MAP.MapDocument(mxdname)
    df = MAP.ListDataFrames(mxd)[0]

    for (layername, fc) in layers:
        annolayer = MAP.ListLayers(mxd, layername, df)[0]
        outputfc = os.path.join(workspace, fc)
        __convert_anno(annolayer, outputfc)
        __fix_anno(outputfc)
        pass
    del mxd  # Release schema locks, hopefully.

    arcpy.env.workspace = workspace
    __repair_seemap("seemap_anno")

    return
def GetDataframe(mxd, dfname):		
    """ Return the named dataframe object from an MXD. """		
    df = None		
    try:		
        df = MAP.ListDataFrames(mxd, dfname)[0]		
    except Exception as e:		
        aprint("Dataframe not found. Make sure it is named '%s'. \"%s\"" % (dfname,e))		
    return df		
def mxd_bookmarks(in_map_document, in_data_frame=None):

    mxd = mapping.MapDocument(in_map_document)
    df = mapping.ListDataFrames(mxd, )

    in_data_frame = "New Data Frame 2"

    mxd = mapping.MapDocument(r"C:\Users\AMarinelli\Desktop\Frames.mxd")
    if in_data_frame is None:
        df = mapping.ListDataFrames(mxd)[0]
    else:
        try:
            df = mapping.ListDataFrames(mxd, in_data_frame)[0]
        except IndexError as detail:
            print 'Data Frame not found:', detail
        else:
            print 'Unknown Error'

    print df.name
Beispiel #5
0
def addlayertotoc(o):
    # Set up the dataframe to display the shapes
    mxd = am.MapDocument("CURRENT")
    # get the data frame
    df = am.ListDataFrames(mxd, "*")[0]
    # create a new layer
    newlayer = am.Layer(o)
    # add the layer to the map at the bottom of the TOC in data frame 0
    ap.mapping.AddLayer(df, newlayer, "BOTTOM")
    ap.RefreshActiveView()
    ap.RefreshTOC()
    del mxd, df, newlayer
Beispiel #6
0
def define_parameters(mxd, data_frame, layer_name):
    '''function to identify the layer for generating reports
    :param mxd: path to a ArcMap Document
    :param data_frame: data frame name
    :param layer_name: name of the layer to be used in reports'''

    map_document = mapping.MapDocument(mxd)

    df = mapping.ListDataFrames(map_document, data_frame)[0]

    lyr = mapping.ListLayers(map_document, layer_name, df)[0]

    return lyr
Beispiel #7
0
def show_dataframes(mxd):
    # Use the list of data frames so report order will be correct.
    l_df = MAP.ListDataFrames(mxd)
    print(" DATA FRAMES:")
    for df in l_df:
        elm = MAP.ListLayoutElements(mxd, wildcard=df.name)[0]
        print("    Dataframe:           " + elm.name)
        print("    X Position:          " + str(elm.elementPositionX))
        print("    Y Position:          " + str(elm.elementPositionY))
        print("    Height:              " + str(elm.elementHeight))
        print("    Width:               " + str(elm.elementWidth))
        print()

        show_layers(mxd, df)
def getMapNumbers():

    global mapnumberlist

    if mapfilename != arcpy.mapping.MapDocument('current').filePath:
        mapnumberlist = None

    if mapnumberlist is None:

        mapnumberlist = []
        MXD = MAP.MapDocument("CURRENT")

        if len(MAP.ListDataFrames(MXD, "MainDF")) > 0:
            mainDF = MAP.ListDataFrames(MXD, "MainDF")[0]
            if len(MAP.ListLayers(MXD, OrmapLayers.MAPINDEX_LAYER,
                                  mainDF)) > 0:
                MapIndex = MAP.ListLayers(MXD, OrmapLayers.MAPINDEX_LAYER,
                                          mainDF)[0]
                orgDefQuery = MapIndex.definitionQuery
                MapIndex.definitionQuery = ""
                mapIndexCursor = arcpy.SearchCursor(MapIndex.name, "", "",
                                                    "MAPNUMBER")

                row = mapIndexCursor.next()

                # Create an empty list
                while row:
                    if row.MAPNUMBER not in mapnumberlist:
                        mapnumberlist.append(row.MAPNUMBER)
                    row = mapIndexCursor.next()

                mapnumberlist.sort()
                MapIndex.definitionQuery = orgDefQuery
    else:
        pass
    return mapnumberlist
Beispiel #9
0
 def load_comarca_values_cmb(self):
     list1 = []
     #Acces to the MDX file
     path_mxd = r"MapasInterpolacion.mxd"
     mxd = map.MapDocument(path_mxd)
     #Acces to the list of layers
     dataframe = map.ListDataFrames(mxd)[0]        
     layers = map.ListLayers(mxd,"",dataframe)
     for layer in layers:
         #if layer.name == btn_layer.text():
         if layer.name == self.rbtn_zoom_to_comarca.text():
             cursor = arcpy.da.SearchCursor(layer, ['COMARCA_'])
             self.cmb_zoom_to_comarca.clear()
             for row in cursor:
                 self.cmb_zoom_to_comarca.addItems(row)
    def loadMXD(self):
        '''
        @param: self
        @brief: Carga el archivo mxd
        :return: None
        '''

        # Cargamos el mxd
        self.mxd = mapping.MapDocument(MXD_PATH)
        # Obtenemos los dataframes
        self.dataframes = mapping.ListDataFrames(self.mxd)

        # Activamos los componentes que están inactivos por defecto
        # (checkboxes, lineedit, ...)
        self.txt_title.setEnabled(True)
        self.check_scale.setEnabled(True)
        self.check_legend.setEnabled(True)
        self.line_edit_df_1.setEnabled(True)
        self.line_edit_df_2.setEnabled(True)

        # Añadimos los nombres de los dataframes a los LineEdits
        self.line_edit_df_1.setText(self.dataframes[0].name)
        self.line_edit_df_2.setText(self.dataframes[1].name)

        # Obtenemos los elementos del Layout que nos interesan
        # para generar los dos tipos de mapas (moviendo los elementos)
        self.dataframe1_scalebar = mapping.ListLayoutElements(
            self.mxd, '', 'data-frame-1-scale-bar')[0]
        self.dataframe1_scaletext = mapping.ListLayoutElements(
            self.mxd, '', 'data-frame-1-scale-text')[0]
        self.dataframe2_scalebar = mapping.ListLayoutElements(
            self.mxd, '', 'data-frame-2-scale-bar')[0]
        self.dataframe2_scaletext = mapping.ListLayoutElements(
            self.mxd, '', 'data-frame-2-scale-text')[0]

        self.legend_title = mapping.ListLayoutElements(self.mxd, '',
                                                       'legend-title')[0]
        self.legend_df1 = mapping.ListLayoutElements(self.mxd, '',
                                                     'legend-df-1')[0]
        self.legend_df2 = mapping.ListLayoutElements(self.mxd, '',
                                                     'legend-df-2')[0]

        self.map_title = mapping.ListLayoutElements(self.mxd, '', 'title')[0]

        self.dataframe1 = mapping.ListLayoutElements(self.mxd, '',
                                                     'data-frame-1')[0]
        self.dataframe2 = mapping.ListLayoutElements(self.mxd, '',
                                                     'data-frame-2')[0]
    def add_layer_to_mxd(self, filename):
        """
        Method for applying symbology to the in-memory layer
        and adding it to a template MXD file for output

        :param str filename: Name of the final output file for adding to the application
        """

        df = mapping.ListDataFrames(self.mxd, "")
        create_layer = mapping.Layer(filename)

        ApplySymbologyFromLayer_management(
            create_layer,
            os.path.join(self.output_location, "least_squares.lyr"))
        mapping.AddLayer(df[0], create_layer, "BOTTOM")

        self.output_image("idwout.jpg")
Beispiel #12
0
 def zoomExtractMXD(parcel):
     #Variables
     mxd = MAP.MapDocument(mxdC)
     df = MAP.ListDataFrames(mxd)[0]
     parcelLyr = MAP.ListLayers(mxd, "Parcels", df)[0]
     jpg = os.path.join(outJPG, "%s") % (parcel)
     #Update Layers
     whereClause = "ACCOUNT ='%s'" % parcel
     arcpy.SelectLayerByAttribute_management(parcelLyr, "NEW_SELECTION", whereClause)
     #Make sure Account Exists
     getCount = arcpy.GetCount_management(parcelLyr)
     theCount = int(getCount.getOutput(0))
     if theCount >= 1:
         df.extent = parcelLyr.getSelectedExtent(True)
         df.scale *= 1.1
         #Update Text
         updatetext1 = MAP.ListLayoutElements(mxd, "TEXT_ELEMENT", "ACCOUNT")[0]
         updatetext1.text = parcel
         #Export to JPG
         MAP.ExportToJPEG(mxd, jpg)
         #Release MXD
         del mxd
     else:
         noAcctLog()
Beispiel #13
0
import arcpy.mapping as mapping
mxd = mapping.MapDocument("CURRENT")
frames = mapping.ListDataFrames(mxd,"C*")
for df in frames:
    print df.name
Beispiel #14
0
#-------------------------------------------------------------------------------
# GRAPHS
#-------------------------------------------------------------------------------
import arcpy
import arcpy.mapping as map
import arcgisscripting

path = r"C:\Users\laboratorios\ELVLC\session6\session6.mxd"
mxd = map.MapDocument(path)
graphic_list = map.ListLayoutElements(mxd, "TEXT_ELEMENT")
df = map.ListDataFrames(mxd)[0]
layer = map.ListLayers(mxd, "", df)[0]
layer_muni = map.ListLayers(mxd, "", df)[1]
cur = arcpy.SearchCursor(layer)
row = cur.next()
while row:
    name = row.getValue("NOMBRE")
    code = row.getValue("PROVI")
    area = row.getValue("AREA") / 1000000
    perimeter = row.getValue("PERIMETER") / 1000
    name = row.getValue("NOMBRE")
    query = '"NOMBRE" = ' + "'" + name + "'"
    arcpy.SelectLayerByAttribute_management(layer, "NEW_SELECTION", query)
    df.zoomToSelectedFeatures()
    graphic_list = map.ListLayoutElements(mxd, "TEXT_ELEMENT")
    for graphic in graphic_list:
        if graphic.name == "txt_name":
            graphic.text == name
        if graphic.name == "txt_vode":
            graphic.text = str(cod)
        if graphic.name == "txt_area":
Beispiel #15
0
                pass

            elif "Iloilo Province" in mapdoc:
                mdoc_name = os.path.basename(mapdoc).split('.')[0]
                print '%d. %s' % (count, mdoc_name)

                mxd = mp.MapDocument(mapdoc)

                # save a backup of the mxd
                backup_mxd = os.path.join(backup_dir, mdoc_name + '.mxd')
                print "Saving as %s" % backup_mxd

                #shutil.copy(mapdoc, backup_mxd)

                # update and insert layer
                main_df = mp.ListDataFrames(mxd)[1]
                main_lyrs = mp.ListLayers(mxd, "", main_df)

                for lyr in main_lyrs:
                    lyr_name = lyr.name

                    if "Sea" in lyr_name:
                        lyr.transparency = 0
                    elif "Contours" in lyr_name:
                        print "Updating %s" % lyr_name
                        mp.UpdateLayer(main_df, lyr, ref_lyr)
                    elif "Bathymetry" in lyr_name:
                        print "Removing %s" % lyr_name
                        mp.RemoveLayer(main_df, lyr)
                    else:
                        pass
Beispiel #16
0
#-------------------------------------------------------------------------------
# LAYERS ON OFF
#-------------------------------------------------------------------------------
import arcpy
import arcpy.mapping as map #cambio el nombre del modulo

#Definicion de variables
ruta_mxd = 'CURRENT'
estado = arcpy.GetParameter(0) #parametro de tipo booleano (devuelve 0-1)
arcpy.AddMessage(estado) #muestra el valor de estado en la caja de mensajes
mxd = map.MapDocument(ruta_mxd) #acceso al proyecto
df = map.ListDataFrames(mxd)[0] #acceso al primer mapa de la lista (dataframe)
#Acceso a todas las capas y cambio de su estado de visibilidad
for c in map.ListLayers(mxd,"",df):
    c.visible = estado

#Refresco de la vista y de la TOC
arcpy.RefreshActiveView()
arcpy.RefreshTOC()

#liberacion de memoria
del mxd
del df
del c

#-------------------------------------------------------------------------------
# MOVE LAYERS
#-------------------------------------------------------------------------------
import arcpy
import arcpy.mapping as map #cambio el nombre del modulo
Beispiel #17
0
import arcpy.mapping as ma
mxd = ma.MapDocument("CURRENT")
df = ma.ListDataFrames(mxd)[0]
lyrs = ma.ListLayers(mxd, "IceUV*")
for i in range(len(lyrs)):
    ma.UpdateLayer(df, lyrs[i], lyrs[-1])
Beispiel #18
0
import arcpy.mapping as mapping
mxd = mapping.MapDocument("CURRENT")
df = mapping.ListDataFrames(mxd, "Crime")[0]
refLayer = mapping.ListLayers(mxd, "SD_Stream", df)[0]
insertLayer = mapping.Layer(
    r'C:\SIGS\work\moverte\SHP\Tehuacan_Cuicatlan.gdb\Linea_transmision')
mapping.InsertLayer(df, refLayer, insertLayer, "BEFORE")
Beispiel #19
0
import arcpy.mapping as mapping
mxd = mapping.MapDocument("CURRENT")
for df in mapping.ListDataFrames(mxd):
    if df.name == "New_Micro":
        mapping.ExportToPDF(
            mxd, r"C:\\EsriTraining\\PythEveryone\\PythonInArcGIS\\New.pdf",
            df)
        print "list"
Beispiel #20
0
mxd = map.MapDocument(r"C:/gc_work/evl/MXDs/RMSHD_atlas_bel2.mxd")
arcpy.env.overwriteOutput = True

####VARIABLES####
floodmodel = "RMS HD and National Belgium Official "  #user input flood model
cityTitle = "Belgium"
returnperiod = "100 years"
coordinatesystem = "Belge 1972 / Belgian Lambert 72 (EPSG: 31370)"
cellsize = "100 x 100 m"
cityfield = "CRESTA_DES"

try:

    if arcpy.Exists(arcpy.env.workspace):
        arcpy.AddMessage("GDb exists")
        df = map.ListDataFrames(mxd, "Layers")[0]

        FCs = arcpy.ListFeatureClasses()
        BuildingFCs = arcpy.ListFeatureClasses("official_MBBuilding*")
        OfficialFishnetFCs = arcpy.ListFeatureClasses("official_MBFishnet*")
        RMSHDFishnetFCs = arcpy.ListFeatureClasses("rmshd_MBFishnet*")
        CityFCs = arcpy.ListFeatureClasses("rmshd_MBCity*")

        ##            for Bfc, Officialfc, RMSHDfc, Cfc in FCs:
        ##                pass

        for Bfc in BuildingFCs:
            BfcID = str(Bfc.split("_")[2])
            for Officialfc in OfficialFishnetFCs:
                OfficialfcID = str(Officialfc.split("_")[2])
                for RMSHDfc in RMSHDFishnetFCs:
##PageSize = arcpy.GetParameterAsText(1)

#LOAD THE PAGE INFORMATION
import ORMAP_MapConfig as PageConfig
##import ORMAP_18x20MapConfig
##import ORMAP_18x24MapConfig
##if PageSize=='18x20':
##    PageConfig = ORMAP_18x20MapConfig
##else:
##    PageConfig = ORMAP_18x24MapConfig

#REFERENCE MAP DOCUMENT
MXD = MAP.MapDocument("CURRENT")

#REFERENCE EACH DATAFRAME - only mainDF is required.
if len(MAP.ListDataFrames(MXD, "MainDF")) > 0:
    mainDF = MAP.ListDataFrames(MXD, "MainDF")[0]
else:
    sys.exit(
        "Unable to find a DataFrame named mainDF.  Please make sure default dataframe is named 'mainDF'."
    )
locatorDF = None
if len(MAP.ListDataFrames(MXD, "LocatorDF")) > 0:
    locatorDF = MAP.ListDataFrames(MXD, "LocatorDF")[0]
sectDF = None
if len(MAP.ListDataFrames(MXD, "SectionsDF")) > 0:
    sectDF = MAP.ListDataFrames(MXD, "SectionsDF")[0]
qSectDF = None
if len(MAP.ListDataFrames(MXD, "QSectionsDF")) > 0:
    qSectDF = MAP.ListDataFrames(MXD, "QSectionsDF")[0]
######################################################################
## UpdateMxd.py
##
## results script without pseudocode
######################################################################

## Step 1
import arcpy.mapping as MAP

mxd = MAP.MapDocument(r"C:\Student\PYTH\Map_production\CorvallisMeters.mxd")
df = MAP.ListDataFrames(mxd)[0]

## Step 2
updateLayer = MAP.ListLayers(df, "ParkingMeters")[0]
sourceLayer = MAP.Layer(r"C:\Student\PYTH\Map_production\ParkingMeters.lyr")
MAP.UpdateLayer(df, updateLayer, sourceLayer, True)

addLayer = MAP.Layer(r"C:\Student\PYTH\Map_production\Schools.lyr")
MAP.AddLayer(df, addLayer)

refLayer = MAP.ListLayers(df, "Schools")[0]

## This is the tricky step.  The order of the arguments appears to be backwards.
MAP.MoveLayer(df, refLayer, updateLayer, "BEFORE")

## Step 3
mxd.title = "Corvallis Meters Map"
elemList = MAP.ListLayoutElements(mxd, "TEXT_ELEMENT")

for elem in elemList:
    if elem.name == "Corvallis Meters":
Beispiel #23
0
# ---------------------------------------------------------------------------

import os, sys, arcpy, arcpy.mapping as MAP

sys.path.append(os.path.dirname(__file__).replace(
    'Scripts', 'Config'))  #path to config files
import ORMAP_LayersConfig as OrmapLayers

#IMPORT PARAMETERS
MapNumber = arcpy.GetParameterAsText(0)

#REFERENCE MAP DOCUMENT
MXD = MAP.MapDocument("CURRENT")

#COLLECT DATAFRAME INFORMATION
if len(MAP.ListDataFrames(MXD, "MainDF")) > 0:
    mainDF = MAP.ListDataFrames(MXD, "MainDF")[0]
else:
    sys.exit(
        "Unable to find a DataFrame named mainDF.  Please make sure default dataframe is named 'mainDF'."
    )

#REFERENCE PAGELAYOUT TABLE
pageLayoutRow = None
if len(MAP.ListTableViews(MXD, OrmapLayers.PAGELAYOUT_TABLE, mainDF)) > 0:
    pageLayoutTable = MAP.ListTableViews(MXD, OrmapLayers.PAGELAYOUT_TABLE,
                                         mainDF)[0]
    pageLayoutCursor = arcpy.SearchCursor(pageLayoutTable.name,
                                          "MapNumber = '" + MapNumber + "'")
    pageLayoutRow = pageLayoutCursor.next()
else:
mxd = mp.MapDocument(mapDoc)

rasDir2 = "F:\\NFIE_SI_2016\\groupProject\\postprocessOutput\\rasters\\composites\\"
outlyrDir = "F:\\NFIE_SI_2016\\groupProject\\postprocessOutput\\rasters\\layers\\"

# Source layers that will be used for symbology reference
fldext_srcLyr = mp.Layer(outlyrDir + "fldext_source_stretch.lyr")
wd_srcLyr = mp.Layer(outlyrDir + "wd_source_stretch.lyr")
fv_srcLyr = mp.Layer(outlyrDir + "fv_source_stretch.lyr")
crit_srcLyr = mp.Layer(outlyrDir + "crit_source_stretch.lyr")

spatialRef = arcpy.SpatialReference(
    3857)  # 3857 is code for WGS_1984_Web_Mecator (auxiliary sphere)

# Remove all current possible layers in the MXD
for df in mp.ListDataFrames(mxd):
    for lyr in mp.ListLayers(mxd, "*", df):
        mp.RemoveLayer(df, lyr)

# Set up raster list
dirList2 = os.listdir(rasDir2)

# List the files found in dirList with their full pathname
rasList2 = [
    rasDir2 + filename for filename in dirList2 if filename.endswith(".tif")
]

# Set up loop for adding raster layers to MXD
for ras in rasList2:
    rasName2 = os.path.basename(ras[:-4])
    if "Per" in rasName2:
# Setup status output
scriptName = 'mf_ddp_extents_to_polys.py'
StartTime = time.strftime("%#c", time.localtime())
startText = "____________________Script started successfully.____________________"
arcpy.AddMessage(" " * 3)
arcpy.AddMessage("         -<>-<>-<>-" * 3)
arcpy.AddMessage(" ")
arcpy.AddMessage(startText)
arcpy.AddMessage("\n")
arcpy.AddMessage(StartTime)


# Setup 
mxd = mapping.MapDocument("CURRENT")  
dataframe = mapping.ListDataFrames(mxd, "*")[0]  

  
# Main

for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):  
     mxd.dataDrivenPages.currentPageID = pageNum  
     frameExtent = dataframe.extent    
     XMAX = frameExtent.XMax    
     XMIN = frameExtent.XMin    
     YMAX = frameExtent.YMax    
     YMIN = frameExtent.YMin    
     pnt1 = arcpy.Point(XMIN, YMIN)    
     pnt2 = arcpy.Point(XMIN, YMAX)    
     pnt3 = arcpy.Point(XMAX, YMAX)    
     pnt4 = arcpy.Point(XMAX, YMIN)    
Beispiel #26
0
# (2)磁盘地图文档
import arcpy.mapping as mapping

path = r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2.mxd"
mxd = mapping.MapDocument(path)
layers = mapping.ListLayers(mxd)
for lyr in layers:
    print(lyr)
# (3)遍历地图文档所有数据框的所有图层并将所有图层依次添加到每个数据框
# 谨慎操作,循环次数过多,ArcGIS容易崩溃
import arcpy
import arcpy.mapping as mapping

mxd = mapping.MapDocument(
    r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd")
ldfs = mapping.ListDataFrames(mxd)
for ldf in ldfs:
    print(ldf.name)
    layers = mapping.ListLayers(mxd)
    for lyr in layers:
        mapping.AddLayer(ldf, lyr, "AUTO_ARRANGE")
        arcpy.RefreshActiveView()
        arcpy.RefreshTOC()
        print(lyr.name)
# (4)将第二个数据框的图层添加到第一个数据框
import arcpy.mapping as mapping

mxd = mapping.MapDocument(
    r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd")
ldf1 = mapping.ListDataFrames(mxd)[0]
ldf2 = mapping.ListDataFrames(mxd)[1]
Beispiel #27
0
        processedWebmapJson = json.dumps(webMapObj)
        log("Webmap simplified: " + processedWebmapJson)

        # save webmap to text file, this is used to import graphics later
        outWebmapTextFile = open(outWebmapTextFilePath, "w")
        outWebmapTextFile.write(processedWebmapJson)
        outWebmapTextFile.close()

        # convert webmap to mxd
        log("Converting webmap to mxd")
        log("Using holding GDB: ")
        log(newGdbFile)
        convertWebmapResult = mapping.ConvertWebMapToMapDocument(
            processedWebmapJson, None, newGdbFile, None)
        webmapMapDoc = convertWebmapResult.mapDocument
        webmapDataframe = mapping.ListDataFrames(webmapMapDoc)[0]
        mapLayers = mapping.ListLayers(webmapMapDoc)
        webmapMapDoc.saveACopy(generatedMxdFilePath)

        # attributes in webmap features are not generated automatically when converting to a map doc
        # manually process comments attribute and apply to generated featureclasses
        # assumes that order of features in webmap matches order of features in featureclasses
        for layer in mapLayers:
            if layer.supports("dataSource"):
                existingFc = layer.dataSource

                if layer.name == "pointLayer":
                    addCommentsToFc(existingFc, "esriGeometryPoint",
                                    "redline-graphicslayer", "remarks")
                elif layer.name == "polylineLayer":
                    addCommentsToFc(existingFc, "esriGeometryPolyline",
Beispiel #28
0
else:
    print "document doesn?t exist"

#-------------------------------------------------------------------------------
# DESCRIPTION REPORT
#-------------------------------------------------------------------------------
import arcpy
from arcpy import mapping


file = open("report.txt", "w")
mxd = mapping.MapDocument(r"C:\Users\laboratorios\ELVLC\session1\session1.mxd")

mxd_name = mxd.filePath.split("\\")[-1]
file.write(mxd_name+"\n\n")
list_df = mapping.ListDataFrames(mxd)

for df in list_df:
    num_lyr = len(mapping.ListLayers(mxd, "", df))
    file.write(df.name+ ": " + str(num_lyr) + " layers\nn")
    for lyr in mapping.ListLayers(mxd, "", df):
       file.write(df.name + " + " + lyr.name + "\n")
       ext = lyr.getExtent()

       if lyr.isFeatureLayer:
        file.write(lyr.name + " VECTOR\n ")
        file.write((str(((str(ext)).split(" ")[0:4]))) + " \n")
        file.write(lyr.dataSource + " \n\n")
       else:
        file.write(lyr.name + " RASTR\n ")
        file.write(" does not have extent  \n ")
import arcpy
import arcpy.da as da
import arcpy.mapping as harta

arcpy.env.workspace = "t:/IE/bd_ro.mdb"
arcpy.env.overwriteOutput = True

tab_inj = arcpy.GetParameterAsText(0)
tab_ind = arcpy.GetParameterAsText(1)

dh = harta.MapDocument("CURRENT")
df = harta.ListDataFrames(dh, "Layers")[0]

ljt = harta.Layer(tab_inj)
ljt.showLabels = True
harta.AddLayer(df, ljt, "TOP")

llt = harta.Layer(tab_ind)
harta.AddLayer(df, llt, "TOP")

listJud = [rand[0] for rand in da.SearchCursor("judTab", ("sj"))]

for jud in listJud:
    arcpy.SelectLayerByAttribute_management(ljt, "NEW_SELECTION",
                                            "sj='" + jud + "'")
    arcpy.Clip_analysis(llt, ljt, "tabClip")
    arcpy.SelectLayerByAttribute_management(ljt, "CLEAR_SELECTION")
    listSeg = [rd[0] for rd in da.SearchCursor("tabClip", ("SHAPE@LENGTH"))]
    sl = sum(listSeg)
    crs = da.UpdateCursor(ljt, ("Lungime"), "sj='" + jud + "'")
    rand = crs.next()
Beispiel #30
0
                                          "{}_{}".format(fc_name, INACTIVE),
                                          INACTIVE_QUERY),
    }

    # now we want to make a map for each
    for lyr_name, lyr in lyrs.iteritems():
        # the result stored in lyr is a result object, not a layer object
        # getOutput(0) gets the first (and only) output from the
        # MakeFeatureLayer commands, which happens to be a layer object
        lyr = lyr.getOutput(0)

        # open the blank mxd because we can't create them reasonably
        mxd = mapping.MapDocument(mxd_path)

        # have to get the first (and only) dataframe
        df = mapping.ListDataFrames(mxd)[0]

        # now we can add the layer object we pulled out above
        mapping.AddLayer(df, lyr)

        # let's save the modified mxd to a new file
        outmxd = os.path.join(map_dir, "{}_{}.mxd".format(fc_name, lyr_name))
        print "Writing map doc {}".format(outmxd)
        mxd.saveACopy(outmxd)

        # clean up the mxd object
        del mxd

#########################################################################
### The below would be useful if it made any sense whatsoever as to
### what one needs to do with a sddraft file to setup the sd as