def getFile(self):
        '''
        @param: self
        @brief: Obtiene los datos del MXD seleccionado
        @return: None
        '''

        # Diálogo nativo para elegir fichero
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.ExistingFile)
        # Solo mostrar archivos con extensión shp
        dlg.setFilter("shapefile (*.shp)")

        if dlg.exec_():
            # Obtenemos la ruta del archivo
            filepath = map(str, list(dlg.selectedFiles()))[0]

            # Eliminamos las capas (que hayan) en los dataframes
            self.deleteLayers()

            # Mostramos la ruta en el label
            self.label_shp_path.setText(filepath)

            # Creamos la capa a partir de la ruta
            layer = mapping.Layer(filepath)

            # Añadimos la capa a los dataframes
            self.addLayer(layer)

            # Actualizamos la simbología de las capas del dataframe
            [
                mapping.UpdateLayer(df, l, self.GRADUATED_COLORS)
                for df in self.dataframes
                for l in mapping.ListLayers(self.mxd, '', df)
            ]

            # Creamos una variable de clase que contendrá las capas
            self.layers = mapping.ListLayers(self.mxd)

            # Obtenemos los campos de la capa
            fieldnames = map(lambda x: x.name,
                             arcpy.ListFields(layer.dataSource))
            # print fieldnames

            # Limpiamos los valores que haya en los comboboxes
            [combo.clear() for combo in self.comboboxes]
            # Añadimos los valores de los campos del shapefile
            [combo.addItems(fieldnames) for combo in self.comboboxes]
            #print self.mxd, self.dataframes, self.layers

            # Activamos los checkboxes
            [check.setEnabled(True) for check in self.checkboxes]
def moveLyr(mapdoc,
            dataframe,
            lyr_to_move,
            reference_lyr_name,
            keyword='AFTER'):
    '''
    Move layer within a dataframe in relation to the reference layer. The keywork determines whether the layer is
    moved above or below the reference layer
    '''

    move_lyr = mp.ListLayers(mapdoc, lyr_to_move.name, dataframe)[0]
    ref_lyr = mp.ListLayers(mapdoc, reference_lyr_name, dataframe)[0]
    mp.MoveLayer(df, ref_lyr, move_lyr, keyword)
Exemple #3
0
def make_vis(mxd_cur, df, listlyr):
    for str_lyr in listlyr:
        lyr_cur = mapping.ListLayers(mxd_cur, str_lyr, df)[0]
        lyr_cur.visible = True
        Delete_management(lyr_cur)
    RefreshTOC()
    RefreshActiveView()
Exemple #4
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
Exemple #5
0
def ExportGISProdLyrs(owner_workspace, admin_workspace):
    #similar to CANP, only for layers in another geodatabase, like GISPROD.
    owner = "GIS_CANSYS.SHARED."
    outpre = owner_workspace + "/" + owner

    print "exporting initialized at " + str(datetime.datetime.now())
    destConnection = owner_workspace  #once again, this could be change to the admin workspace
    for lyr in mapping.ListLayers(mxd):
        if lyr.name in gisprodlist:
            try:
                #manipulate the layer name a little bit differently
                lyrname = lyr.name[7:]
                print lyrname + " exporting..."
                outlyrname = lyrname
                outlyrobj = outpre + outlyrname
                Unlock(admin_workspace)
                FeatureClassToFeatureClass_conversion(lyr, destConnection,
                                                      outlyrname, "#", "#",
                                                      "#")
                ChangePrivileges_management(outlyrobj, "readonly", "GRANT",
                                            "AS_IS")
                print lyrname + " exported to " + outlyrname + " " + str(
                    datetime.datetime.now())
            except ExecuteError:
                msgs = GetMessages(2)
                AddError(msgs)
                print msgs
                endingTime = datetime.datetime.now()
                ScriptStatusLogging('CANP_LRS_EXPORT.py',
                                    'ExportGISProdLyrs Function',
                                    scriptFailure, startingTime, endingTime,
                                    GetMessages(2))

                pass
            except (RuntimeError, TypeError, NameError):
                print "TypeError on item" + lyr.name
                endingTime = datetime.datetime.now()
                ScriptStatusLogging('CANP_LRS_EXPORT.py',
                                    'ExportGISProdLyrs Function',
                                    scriptFailure, startingTime, endingTime,
                                    GetMessages(2))

                pass
            except:
                tb = sys.exc_info()[2]
                tbinfo = traceback.format_tb(tb)[0]
                pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(
                    sys.exc_info()[1])
                msgs = "ArcPy ERRORS:\n" + GetMessages(2) + "\n"
                print pymsg + "\n"
                print msgs
                endingTime = datetime.datetime.now()
                ScriptStatusLogging('CANP_LRS_EXPORT.py',
                                    'ExportGISProdLyrs Function',
                                    scriptFailure, startingTime, endingTime,
                                    GetMessages(2))

        else:
            #print lyr.name +" was not in the export list and will be skipped"
            return
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)
def GetLayer(mxd, df, layername):
    """ Return the named layer from an MXD. """
    layer = None		
    try:		
        layer = MAP.ListLayers(mxd, layername, df)[0]		
    except IndexError:		
        print("Can't find layer \"%s\"/\"%s\"." % (df.name, layername))		
    return layer
Exemple #8
0
def applySymbologyToRoutes():
    """Apply a single symbology to all of the carto route feature classes"""

    for lyr in mapping.ListLayers(mxd):
        if 'Carto Routes' in lyr.longName and lyr.isFeatureLayer:
            print lyr.name
            management.ApplySymbologyFromLayer(lyr, symbology)
            #lyr.save()
    mxd.save()
Exemple #9
0
def ListAllLyrs():
    print "layer list initialized at " + str(datetime.datetime.now())
    for lyr in mapping.ListLayers(mxd):
        try:
            lyrname = lyr.name
            print lyrname
        except:
            print "there was a problem with this layer" + str(
                datetime.datetime.now())
            pass
 def deleteLayers(self):
     '''
     @param: self
     @brief: Elimina las capas de los dataframes
     :return: None
     '''
     [
         mapping.RemoveLayer(df, l) for df in self.dataframes
         for l in mapping.ListLayers(self.mxd, '', df)
     ]
Exemple #11
0
def TruncateAndAppend(mxd, TargetLT, TargetST):
	lyrs = mapping.ListLayers(mxd)

	print "Updating data for " +str(lyrs[0])
	TruncateTable_management(TargetST)
	Append_management(lyrs[0], TargetST, "NO_TEST", "#")

	print "Updating data for " +str(lyrs[1])
	TruncateTable_management(TargetLT)
	Append_management(lyrs[1], TargetLT, "NO_TEST", "#")
Exemple #12
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
Exemple #13
0
def ListAllLyrs():
    #function to list all the layers in the MXD/data frame, can be used to compare to printed CANPlist
    print "layer list initialized at " + str(datetime.datetime.now())
    for lyr in mapping.ListLayers(mxd):
        try:
            lyrname = lyr.name
            print lyrname
        except:
            print "There was a problem with this layer: " + str(lyr.name)
            endingTime = datetime.datetime.now()
            ScriptStatusLogging(
                'CANP_LRS_EXPORT.py', 'ListAllLyrs Function', scriptFailure,
                startingTime, endingTime,
                'There was a problem with this layer: ' + str(lyr.name))
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
Exemple #15
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 mxd_data_source(folder):
    """
    Given a folder path, search folder directory for mxd files.

    Parameters
    ----------
    folder: string, folder pathway

    Returns
    -------
    result: A sequence of feature class information to store in csv file. For each
    mxd file found, the following information is stored:
    
        map name: string
        map pathway: string
        map feature layer: string
        feature layer pathway: string
    """

    print "\nChecking data sources of each MXD...\n"
    for root, dirs, files in os.walk(folderPath):
        for f in files:
            # Crawl folder for files with .mxd extention
            if f.lower().endswith(".mxd"):
                # Return MXD names and pathways
                mxdName = os.path.splitext(f)[0]
                mxdPath = os.path.join(root, f)
                print "     Checking MXD titled: " + mxdName

                # Return MXD properties
                mxd = mapping.MapDocument(mxdPath)
                # Return list of layers for MXDs
                layers = mapping.ListLayers(mxd, "")
                # Loop layers in MXDs
                for lyr in layers:
                    lyrName = lyr.name
                    # Return data source/pathway for each layer in MXD
                    lyrDatasource = lyr.dataSource if lyr.supports(
                        "dataSource") else "N/A"
                    # Put all these variables in order for the .csv file
                    seq = (mxdName, mxdPath, lyrName, lyrDatasource)
                    yield seq
                del mxd
Exemple #17
0
def ExportCANPLyrs():
    print "exporting initialized at " + str(datetime.datetime.now())
    destConnection = r"D:\SQL61_GIS_CANSYS.sde"
    TableToTable_conversion("MAP_EXTRACT",
                            r"Database Connections/SQL61_GIS_CANSYS.sde",
                            "Map_Extract", "#", "#", "#")
    for lyr in mapping.ListLayers(mxd):
        if lyr.name in CANPlist:
            try:
                lyrname = lyr.name[11:]
                print lyrname + " exporting..."
                outlyrname = "V_" + lyrname
                outlyrobj = destConnection + "\\GIS_CANSYS.DBO." + outlyrname
                FeatureClassToFeatureClass_conversion(lyr, destConnection,
                                                      outlyrname, "#", "#",
                                                      "#")
                ChangePrivileges_management(outlyrobj, "readonly", "GRANT",
                                            "AS_IS")
                print lyrname + " exported to " + outlyrname + " " + str(
                    datetime.datetime.now())
            except ExecuteError:
                msgs = GetMessages(2)
                AddError(msgs)
                print msgs
                pass
            except (RuntimeError, TypeError, NameError):
                print "TypeError on item" + lyr.name
                pass
            except:
                tb = sys.exc_info()[2]
                tbinfo = traceback.format_tb(tb)[0]
                # Concatenate information together concerning the error into a message string
                #
                pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(
                    sys.exc_info()[1])
                msgs = "ArcPy ERRORS:\n" + GetMessages(2) + "\n"
                print pymsg + "\n"
                print msgs

        else:
            #print lyr.name +" was not in the export list and will be skipped"
            pass
Exemple #18
0
    def onClick(self):
        mxd = arcpy.mapping.MapDocument("CURRENT")
        layerList = mapping.ListLayers(mxd)
        self.inFc = layerList[0]
        self.inFcWorkspace = layerList[0].workspacePath
        self.layerName = layerList[0].name
        selectedCount = int(
            arcpy.GetCount_management(layerList[0]).getOutput(0))
        print "Version 1.3"
        print "Selected count: {}".format(selectedCount)

        if selectedCount != 1:
            return

        shapeFieldToRemove = "Shape"
        fieldNames = ["SHAPE@", "OID@", "*"]

        with arcpy.da.SearchCursor(self.inFc,
                                   fieldNames,
                                   explode_to_points=False) as cursor:
            for row in cursor:
                Config.srcFieldNames, Config.srcRow = self.cleanSrcRows(
                    list(cursor.fields), list(row), [shapeFieldToRemove])
                print "Source field names found"
                self.wholeRoad = WholeRoad(
                    row[Config.getFieldIndex("SHAPE@")],
                    row[Config.getFieldIndex("L_F_ADD")],
                    row[Config.getFieldIndex("L_T_ADD")],
                    row[Config.getFieldIndex("R_F_ADD")],
                    row[Config.getFieldIndex("R_T_ADD")])

                self.wholeRoad.setId(row[Config.getFieldIndex("OID@")])
                print "Whole road created"
                break

        pointSelector.enabled = True
        print "Point selector enabled"
Exemple #19
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()
Exemple #20
0
import arcpy
from arcpy import env
from arcpy import mapping

# list layers
mxd = mapping.MapDocument(
    "CURRENT")  # will work even if your project is unsaved
layer_list = mapping.ListLayers(mxd)  # lists everything in the ToC window
sr = arcpy.SpatialReference(4283)  # GDA_94

# Set environment settings
env.workspace = "C:/data"

# GETTING THE REFERENCE OBJECT
REF_OBJ = "REF_OBJ.shp"  # Get the Reference Object (possibly as shape file.)
REF_MBR = ''  # Create a MBR for Reference Object
extent_REF = REF_MBR.extent  # Get the extent of REF_MBR

# GETTING THE TARGET OBJECT
TAR_OBJ = "TAR_OBJ.shp"  # Get the Reference Object (possibly as shape file.)
TAR_MBR = ''  # Create a MBR for Reference Object
extent_TAR = TAR_MBR.extent  # Get the extent of REF_MBR

# CALULATE DISTANCE BETWEEN REF_OBJ & TAR_OBJ
dis_x = abs(abs(extent_TAR.XMin - extent_REF.XMin) + extent_TAR.width)
dis_y = abs(abs(extent_TAR.YMin - extent_REF.YMin) + extent_TAR.height)

# CALULATE BOUNDS OF THE TOTAL SPACE
MIN_x = extent_REF.XMin - dis_x
MAX_x = extent_REF.XMax + dis_x
MIN_y = extent_REF.YMin - dis_y
Exemple #21
0
            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
                        #print 'no'
import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")
print mapping.ListLayers(mxd)
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])
Exemple #24
0
#-------------------------------------------------------------------------------
# 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 ")
        file.write(lyr.dataSource + " \n\n")
file.close()
Exemple #25
0
def show_layers(mxd, df):
    print("    Layers:")
    for lyr in MAP.ListLayers(mxd, "", df):
        show_layer(lyr)
    print()
    path + "06_ArcMap\KM_VolumetricChange.mxd")  #Mapping document
print("Accesing " + mxd.title)

vectorType = "Dune"  #Type of anlaysis (Total, Dune, Tidal) user determined
type = "Erosion"  #Type of vector (Erosion or Deposition) user determined
layerLoc = (path + "15_Layers/" + vectorType + "_" + type + ".lyr")
source = mapping.Layer(layerLoc)
#target = mapping.ListLayers(mxd,'Vectors_' + type + '*',df)
print(source)
#------------------------------------------------------------------------------------------

for df in mapping.ListDataFrames(mxd):
    if (
            df.name == 'ElevationChange'
    ):  #This is a user controlled variable - its whatever the dataframe you put the vectors into is called
        targets = mapping.ListLayers(mxd, 'Vectors_' + type + '*', df)
        for layer in targets:
            print("Updating " + layer.name)
            test = mapping.UpdateLayer(
                df, layer, source, True
            )  #make this a variable and call it in and see if its working
            print(test)
print("Complete")

#---------------------------------------------------------------------------------------------------------
#For use in the python window in ArcMap - this saves time if you have more than 2 comparisons, otherwise manually changing is faster. You have to change the .lyr name and the targets name when switching to tidal and total. If you've already separated te vetors into individual data frames - then do not include line 46 and make the target layer more specific ex: 'Vectors_Erosion_Dune*', this will do a search through all the dataframes you have.

#>>> import arcpy.mapping as mapping
#>>> mxd = mapping.MapDocument("CURRENT")
#>>> source = mapping.Layer(r"M:\01_NPS\01_Gateway\01_SHU\05_Projects\KingmanMills\KM_2012-2019\15_Layers\Dune_erosion.lyr")
#>>> for df in mapping.ListDataFrames(mxd):
Exemple #27
0
'''
Created on Aug 13, 2014
Truncate and Append LRS elements from the Gateway MXD to static features classes in the Gateway SQL server GEodatabase
Moved to Production on Aug 20 2014
@author: kyleg
'''
from arcpy import mapping, Append_management, TruncateTable_management
GDB = r'D:\HNTB_GATEWAY\ProductionMOT\SQL54_GATEWAY15.sde'
mxd = mapping.MapDocument(
    r'D:\HNTB_GATEWAY\ProductionMOT\2014111401_GatewayExec.mxd')

lyrs = mapping.ListLayers(mxd)
#D:\HNTB_GATEWAY\ProductionMOT\SQL54_GATEWAY15.sde\Gateway2015.GATEWAY_SPATIAL.LongTermApproved
TargetLT = r"D:\HNTB_GATEWAY\ProductionMOT\SQL54_GATEWAY15.sde\Gateway2015.GATEWAY_SPATIAL.LongTermApproved"
TargetST = r'D:\HNTB_GATEWAY\ProductionMOT\SQL54_GATEWAY15.sde\Gateway2015.Gateway_Spatial.ShortTermApproved'

print lyrs[0]
TruncateTable_management(TargetST)
Append_management(lyrs[0], TargetST, "NO_TEST", "#")

print lyrs[1]
TruncateTable_management(TargetLT)
Append_management(lyrs[1], TargetLT, "NO_TEST", "#")

#if __name__ == '__main__':
#    pass
FeatureClassToFeatureClass_conversion(r"Database Connections\CANP.sde\NM3.NM_NLT_SRND_SRND_SDO", STAGEDB, "SRND" )
FeatureClassToFeatureClass_conversion(r"Database Connections\CANP.sde\NM3.NM_NLT_CRND_CRND_SDO", STAGEDB, "CRND" )
TableToTable_conversion(r'Database Connections\CANP.sde\KDOT.MV_MAP_EXTRACT', STAGEDB, "Map_Extract")
TableToTable_conversion(r'Database Connections\CANP.sde\NM3.NM_ELEMENTS_ALL', STAGEDB, "ELEMENTS_ALL")
TableToTable_conversion(r'Database Connections\CANP.sde\NM3.NM_MEMBERS_ALL', STAGEDB, "MEMBERS_ALL") #Members takes a long time to copy


#To copy the SECT layer it must be joined to preserve RSE_HE_ID
MakeFeatureLayer_management(r"Database Connections\CANP.sde\NM3.NM3_NET_MAP_SECT_TABLE", "NM_SECT" )
MakeTableView_management(STAGEDB+r"\Elements_ALL", "ELEMENTS")
AddJoin_management("NM_SECT", "RSE_HE_ID", "ELEMENTS", "NE_ID", "KEEP_COMMON")
FeatureClassToFeatureClass_conversion("NM_SECT", STAGEDB, "SECT" )

#Remove the CANP Prod layers
for df in mapping.ListDataFrames(mxd):
    for lyr in mapping.ListLayers(mxd, "", df):
        mapping.RemoveLayer(df, lyr)
RefreshActiveView()

#Start the processing to rebuild layers
MakeFeatureLayer_management(STAGEDB+r"\SRND", "SRND")
SRNDelem = "NE_NT_TYPE = 'SRND' AND NE_VERSION_NO in ('EB', 'NB')"
MakeTableView_management(STAGEDB+r"\ELEMENTS_ALL", "SRND_ELEM", SRNDelem)
AddJoin_management("SRND", "NE_ID", "SRND_ELEM", "NE_ID", "KEEP_COMMON")

#Create the vertices for calibration points
FeatureVerticesToPoints_management("SRND", STAGEDB+"/Calibration_Points_SRND","ALL")
AddXY_management("GIS_CANSYS.DBO.Calibration_Points_SRND")
'''
LocateFeaturesAlongRoutes_lr(ws+"\\"+tempgdb+"/Calibration_Points",ws+"\\"+tempgdb+"/SRND","NE_UNIQUE","0.001 Feet",ws+"\\"+tempgdb+"/CP_SRND","STATE_MILE POINT SR_MEAS","ALL","DISTANCE","ZERO","FIELDS","M_DIRECTON")
AddJoin_management("SECT","RSE_HE_ID","Elements","NE_ID","KEEP_COMMON")
Exemple #29
0
# @author Cindy Williams
# @date 25/06/2013
#
# Loops over an existing spreadsheet with attribute data
# and builds up a definition query to apply to the dataset.
#
# For use in the Python window in ArcMap.
#

from arcpy import da
import arcpy.mapping as MAP

# Input variables
xls = r"C:\Some\Arb\Folder\Data.xlsx\Sheet1$"  # Spreadsheet
mxd = MAP.MapDocument("CURRENT")  # Current map document
lyr = MAP.ListLayers(mxd)[0]  # First layer in the the map
lst_qry = []  # List to hold the query
field_name = "Layer"

# Loops over the spreadsheet using a search cursor.
# Appends each value into the list
with arcpy.da.SearchCursor(xls, field_name) as cursor:
    for row in cursor:
        defn_qry = """ "{0}" = '{1}' """.format(field_name, row[0])
        lst_qry.append(defn_qry)

# Build a string representation of the definition query and apply it to the layer
lyr.definitionQuery = ' OR '.join(lst_qry)

# Refresh ArcMap to see the query applied
arcpy.RefreshActiveView()
Exemple #30
0
# 2、	引用当前的地图文档;
# 3、	引用磁盘上的地图文档;
# 4、	获取地图文档中的图层列表;
# 5、	限制图层列表;
# 6、	缩放所选要素;
# 7、	改变地图范围;
# 8、	添加、插入图层到地图文档;
# 9、	更新图层的符号系统。

# 2 引用当前地图文档
# Notes:需要在ArcGIS中的Python窗口运行该代码
import arcpy.mapping as mapping

mxd = mapping.MapDocument("CURRENT")
mxd.title = "NEW"
layers = mapping.ListLayers(mxd)
for lyr in layers:
    print(lyr)

# 3 引用磁盘上的地图文档
import arcpy.mapping as mapping

path = r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2.mxd"
mxd = mapping.MapDocument(path)
mxd.title = "Crime_Ch2_new"
print(mxd.title)
mxd.saveACopy(r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd")
mxd_new = mapping.MapDocument(
    r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd")
print(mxd_new.title)
layers = mapping.ListLayers(mxd)