def asignasimbologia(layer, campo, num_clases, clases,
                     ruta):  # asigna la simbología y devuelve los intervalos
    mxd = arcpy.mapping.MapDocument("current")  # captura el mxd abierto
    df = arcpy.mapping.ListDataFrames(mxd)[0]  # captura el dataframe
    addlayer = arcpy.mapping.Layer(
        layer)  # instancia el objeto layer de mapping
    arcpy.mapping.AddLayer(df, addlayer)  # añade el layer al mapa o mxd
    lyr = arcpy.mapping.ListLayers(
        mxd, "*" + arcpy.Describe(layer).name +
        "*")[0]  # captura el layer cargado en el mapa
    sourceLayer = arcpy.mapping.Layer(
        ruta + "\\layers\\" + "intervalos_geometricos_alta_media_baja.lyr"
    )  # captura el layer de ejemplo que define la simbología
    arcpy.mapping.UpdateLayer(
        df, lyr, sourceLayer, True
    )  # asigna la simbologia del layer de ejemplo al layer a actualizar
    arcpy.RefreshTOC()  # refresca la tabla de contenido
    arcpy.RefreshActiveView()  # refresca la vista activa
    if lyr.symbologyType == "GRADUATED_COLORS":  # si se tiene simbología de colores graduados
        lyr.symbology.valueField = campo  # asigna el campo para hacer los intervalos
        lyr.symbology.numClasses = num_clases  # asigna el número de clases
        lyr.symbology.classBreakLabels = clases  # asigna los nombre de las clases
    arcpy.RefreshActiveView()  # refresca la tabla de contenido
    arcpy.RefreshTOC()  # refresca la vista activa
    rangos = lyr.symbology.classBreakValues  # captura los intervalos
    return rangos  # devuelve los intervalos
Esempio n. 2
0
def map_create(_dataset, _sde_path, _mxd_folder):
    arcpy.AcceptConnections(_sde_path, True)
    _dataset_name = _sde_path.split('\\')[-1] + '.' + _dataset
    _dataset_path = _sde_path + '/' + _dataset_name
    print(_dataset_path)
    arcpy.env.workspace = _mxd_folder
    mxd_list = arcpy.ListFiles()
    mxd_temp = _mxd_folder + "/" + "Temp.mxd"
    mxd_new = _mxd_folder + "/" + _dataset + ".mxd"
    if _dataset + '.mxd' not in mxd_list:
        log_write(_dataset, "{}.mxd was created".format(_dataset))
        arcpy.Copy_management(mxd_temp, mxd_new)
        # Read MXD file
        _mxd = arcpy.mapping.MapDocument(mxd_new)
        # Read Layers sets
        _layers = arcpy.mapping.ListDataFrames(_mxd, "Layers")[0]
        _layers.name = _dataset  # Layers sets rename
        print(_layers.name)
        # Read feature lists
        arcpy.env.workspace = _dataset_path
        for ft in arcpy.ListFeatureClasses():
            print(ft)
            layer_add = arcpy.mapping.Layer(
                _dataset_path + '/' + ft
            )  # This operation need to add full path in order to keeping the full name of the layer.
            print(layer_add)
            print(layer_add.datasetName)
            arcpy.mapping.AddLayer(_layers, layer_add,
                                   "AUTO_ARRANGE")  # Add layer
            log_write(_dataset,
                      "{1} was added in {0}.mxd".format(_dataset, ft))
        arcpy.RefreshActiveView()
        arcpy.RefreshTOC()
        _mxd.save()
    else:
        _mxd = arcpy.mapping.MapDocument(mxd_new)
        log_write(_dataset, "{}.mxd was Exited".format(_dataset))
        print(arcpy.mapping.ListLayers(_mxd))
        layer_lists = list(map(ly_name, arcpy.mapping.ListLayers(_mxd)))
        print(layer_lists)
        # Read feature lists
        arcpy.env.workspace = _dataset_path
        print(arcpy.ListFeatureClasses())
        for ft in arcpy.ListFeatureClasses():
            if ft not in layer_lists:
                print(ft)
                layer_add = arcpy.mapping.Layer(
                    _dataset_path + '/' + ft
                )  # This operation need to add full path in order to keeping the full name of the layer.
                print(layer_add)
                print(layer_add.datasetName)
                _layers = arcpy.mapping.ListDataFrames(_mxd, _dataset)[0]
                arcpy.mapping.AddLayer(_layers, layer_add,
                                       "AUTO_ARRANGE")  # Add layer
                log_write(_dataset,
                          "{1} was added in {0}.mxd".format(_dataset, ft))
        arcpy.RefreshActiveView()
        arcpy.RefreshTOC()
        _mxd.save()
def asignasimbologia(layer, campo, num_clases, clases, tipo_clasificacion,
                     ruta):  # asigna la simbología y devuelve los intervalos
    tipo_dict = {
        "Intervalos_Geometricos": "intervalos_geometricos_alta_media_baja",
        "Intervalos_Iguales": "intervalos_iguales_3clases",
        "Quantiles": "quantiles_3clases",
        "Natural_Breaks_(jenks)": "natural_breaks_jenks_3clases",
        "Intervalos_Manuales": "natural_breaks_jenks_3clases"
    }
    mxd = arcpy.mapping.MapDocument("current")  # captura el mxd abierto
    df = arcpy.mapping.ListDataFrames(mxd)[0]  # captura el dataframe
    addlayer = arcpy.mapping.Layer(
        layer)  # instancia el objeto layer de mapping
    arcpy.mapping.AddLayer(df, addlayer)  # añade el layer al mapa o mxd
    try:
        lyr = arcpy.mapping.ListLayers(
            mxd, "*" + arcpy.Describe(layer).name +
            "*")[0]  # captura el layer cargado en el mapa
    except:
        lyr = arcpy.mapping.ListLayers(mxd, "*" + layer + "*")[0]
    sourceLayer = arcpy.mapping.Layer(
        ruta + "\\layers\\" + tipo_dict[tipo_clasificacion] +
        ".lyr")  # captura el layer de ejemplo que define la simbología
    ##    arcpy.mapping.UpdateLayer(df, lyr, sourceLayer, True) # asigna la simbologia del layer de ejemplo al layer a actualizar
    arcpy.RefreshTOC()  # refresca la tabla de contenido
    arcpy.RefreshActiveView()  # refresca la vista activa
    if lyr.symbologyType == "GRADUATED_COLORS":  # si se tiene simbología de colores graduados
        lyr.symbology.valueField = campo  # asigna el campo para hacer los intervalos
        arcpy.AddMessage(campo)
        arcpy.AddMessage(num_clases)
        lyr.symbology.numClasses = num_clases  # asigna el número de clases
        if tipo_clasificacion in ("Intervalos_Manuales"):
            if len(intervalos) < num_clases + 1:

                arcpy.AddError("###################################")
                if len(intervalos) == 0:
                    arcpy.AddError("Debe introducir los intervalos")
                else:
                    arcpy.AddError("Debe introducir %s intervalos" %
                                   (str(len(intervalos) + 1)))
                arcpy.AddError("###################################")
                sys.exit()
            lyr.symbology.numClasses = num_clases  # asigna el número de clases
            lyr.symbology.classBreakValues = intervalos  # captura los intervalos

            if label_intervalos == "false":
                lyr.symbology.classBreakLabels = clases  # asigna los nombre de las
        else:
            if label_intervalos == "false":
                lyr.symbology.classBreakLabels = clases  # asigna los nombre de las

    arcpy.RefreshActiveView()  # refresca la tabla de contenido
    arcpy.RefreshTOC()  # refresca la vista activa
    rangos = lyr.symbology.classBreakValues  # captura los intervalos
    return rangos  # devuelve los intervalos
def queryCapasAuxiliares(ubigeo, mxd):
    for i in arcpy.mapping.ListLayers(mxd):
        if i.name == 'RED HIDROGRAFICA':
            i.definitionQuery = "UBIGEO = '{}'".format(ubigeo)
            i.visible = True
            arcpy.RefreshTOC()
            arcpy.RefreshActiveView()
        elif i.name == 'CURVAS NIVEL':
            i.definitionQuery = "UBIGEO = '{}'".format(ubigeo)
            i.visible = True
            arcpy.RefreshTOC()
            arcpy.RefreshActiveView()
Esempio n. 5
0
    def onSelChange(self, selection):

        mxd = arcpy.mapping.MapDocument(
            r'C:\Users\Administrator\Desktop\medad\python\Work\Mpy\Test_Start_proc\Tamplate\EditTazar.mxd'
        )
        df = arcpy.mapping.ListDataFrames(mxd)[0]
        lyrs = arcpy.mapping.ListLayers(mxd, '*', df)
        for lyr in lyrs:
            arcpy.SelectLayerByAttribute_management(lyr, "CLEAR_SELECTION")
            if lyr.isFeatureLayer:
                if str(os.path.basename(lyr.dataSource)) in [
                        "Errors_Polygon", "Errors_Line", "Errors_Point"
                ]:
                    if selection == "Errors_Polygon":
                        if str(os.path.basename(
                                lyr.dataSource)) == "Errors_Polygon":
                            lyr.visible = True
                        else:
                            lyr.visible = False
                    if selection == "Errors_Line":
                        if str(os.path.basename(
                                lyr.dataSource)) == "Errors_Line":
                            lyr.visible = True
                        else:
                            lyr.visible = False
                    if selection == "Errors_Point":
                        if str(os.path.basename(
                                lyr.dataSource)) == "Errors_Point":
                            lyr.visible = True
                        else:
                            lyr.visible = False
        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()
Esempio n. 6
0
def change_legend(map_document, flag_="default"):
    # flag = depth (X = 677, Y = 347, W =42, H  = 73 )
    # flag = danger (X = 677, Y = 318, W =42, H = 73 )
    # flag = default  (X = 850 )

    legend_type = "LEGEND_ELEMENT"
    legend_name = "LegendDepthAndDanger"
    if flag_ == "default":
        for elm in arcpy.mapping.ListLayoutElements(map_document, legend_type,
                                                    legend_name):
            elm.elementPositionX = 850
            change_frame(map_document, flag_)
            # elm.elementPositionY = 325
    elif flag_ == "depth":
        for elm in arcpy.mapping.ListLayoutElements(map_document, legend_type,
                                                    legend_name):
            elm.elementPositionX = 677
            elm.elementPositionY = 347
            change_frame(map_document, flag_)
    elif flag_ == "danger":
        for elm in arcpy.mapping.ListLayoutElements(map_document, legend_type,
                                                    legend_name):
            elm.elementPositionX = 677
            elm.elementPositionY = 318
            change_frame(map_document, flag_)
    arcpy.RefreshTOC()
    arcpy.RefreshActiveView()
Esempio n. 7
0
def change_frame(map_document, flag_="default"):
    # flag = depth (X = 670, Y = 212, W =167, H  = 137 )
    # flag = danger (X = 670, Y = 236, W =167, H = 87 )
    # flag = default  (X = 850 )
    legend_type = "GRAPHIC_ELEMENT"
    frame_depth = "Frame_Depth"
    frame_danger = "Frame_Danger"
    if flag_ == "default":

        for elm in arcpy.mapping.ListLayoutElements(map_document, legend_type,
                                                    frame_danger):
            elm.elementPositionX = 850
        for elm in arcpy.mapping.ListLayoutElements(map_document, legend_type,
                                                    frame_depth):
            elm.elementPositionX = 900
            # elm.elementPositionY = 325
    elif flag_ == "depth":
        for elm in arcpy.mapping.ListLayoutElements(map_document, legend_type,
                                                    frame_danger):
            elm.elementPositionX = 850
        for elm in arcpy.mapping.ListLayoutElements(map_document, legend_type,
                                                    frame_depth):
            elm.elementPositionX = 670
            # elm.elementPositionY = 210
            elm.elementPositionY = 213
    elif flag_ == "danger":
        for elm in arcpy.mapping.ListLayoutElements(map_document, legend_type,
                                                    frame_danger):
            elm.elementPositionX = 670
            elm.elementPositionY = 236
        for elm in arcpy.mapping.ListLayoutElements(map_document, legend_type,
                                                    frame_depth):
            elm.elementPositionX = 900
    arcpy.RefreshTOC()
    arcpy.RefreshActiveView()
Esempio n. 8
0
 def onClick(self):
     folder_path = pythonaddins.OpenDialog('Select Folder', False, r'C:\Program Files (x86)\ArcGIS','Add')
     #Ext = [".shp"]
     Ext = [".tif",".img",".pix",".dat"]
     if folder_path == None:
         pythonaddins.MessageBox("请选择一个文件夹",'消息',0)
         exit
     else:
         shpsList = []
         for root,dirs,files in os.walk(folder_path):
             for file in files:
                 filepath = os.path.join(root,file)
                 if os.path.splitext(filepath)[1] in Ext:
                     shpsList.append(filepath)
         mxd = arcpy.mapping.MapDocument('current')
         df = arcpy.mapping.ListDataFrames(mxd)[0]
         i = 1
         for fc in shpsList:
             layer_name = os.path.splitext(os.path.basename(fc))[0] + str(i)
             print layer_name
             arcpy.MakeRasterLayer_management(fc, layer_name)
             del layer_name
             i = i + 1
             arcpy.RefreshTOC()
         pythonaddins.MessageBox("栅格影像数据加载完成",'消息',0)
Esempio n. 9
0
def removelayers():
    mxd = arcpy.mapping.MapDocument(u'current')
    df = arcpy.mapping.ListDataFrames(mxd)
    for layer in arcpy.mapping.ListLayers(df[0]):
        if layer.isFeatureLayer and layer.isBroken:
            arcpy.mapping.RemoveLayer(df, layer)
    arcpy.RefreshTOC()
Esempio n. 10
0
def make_vis(mxd_cur, df, list_lyr):
    for str_lyr in list_lyr:
        lyr_cur = arcpy.mapping.ListLayers(mxd_cur, str_lyr, df)[0]
        lyr_cur.visible = True
        arcpy.Delete_management(lyr_cur)
    arcpy.RefreshTOC()
    arcpy.RefreshActiveView()
Esempio n. 11
0
def AddCLUSRoadsToMap():
    import arcpy
    import os
    wrk = r'\\spatialfiles2.bcgov\archive\FOR\VIC\HTS\ANA\PROJECTS\CLUS\Data\Roads'
    mxd = arcpy.mapping.MapDocument("CURRENT")
    df = mxd.activeDataFrame
    for lyrs in arcpy.mapping.ListLayers(mxd, "Symbology", df):
        print "Got Symbology Layer {0}".format(lyrs)
        symLyr = lyrs

    wrk = r'\\spatialfiles2.bcgov\archive\FOR\VIC\HTS\ANA\PROJECTS\CLUS\Data\Roads'
    for d in os.listdir(wrk):
        if d.find("CLUS_IntRoads_TSA") == 0:
            tsa = d[17:19]
            if int(tsa) > 44:
                fc = os.path.join(wrk, d, "Data", d[:-4])

                lyrTmp = 'CLUS_IntRoads_TSA{0}'.format(tsa)
                arcpy.MakeFeatureLayer_management(fc, lyrTmp)
                #arcpy.ApplySymbologyFromLayer_management(lyrTmp, symLyr)
                arcpy.ApplySymbologyFromLayer_management(lyrTmp, "Symbology")
                print 'Adding Layer {0}'.format(fc)
                #arcpy.mapping.AddLayer(df,lyrTmp)

    arcpy.RefreshTOC()
Esempio n. 12
0
    def cook(self, recipe):
        arcpy.env.addOutputsToMap = False

        self.disableLayers()
        self.removeLayers()

        self.mapReport = MapReport(recipe.product)
        if recipe:
            for recipe_frame in recipe.map_frames:
                arc_data_frame = arcpy.mapping.ListDataFrames(
                    self.mxd, recipe_frame.name).pop()

                for recipe_lyr in recipe_frame.layers:
                    # Do things at an individual layer level
                    self.process_layer(recipe_lyr, arc_data_frame)

                # Do things at an map/data frame level
                self.apply_frame_crs_and_extent(arc_data_frame, recipe_frame)

        # Do things at a map layout level
        self.enableLayers()
        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()
        arcpy.env.addOutputsToMap = True
        self.showLegendEntries()
        self.mxd.save()

        if recipe:
            self.updateTextElements(recipe)
            self.mxd.save()
Esempio n. 13
0
def createMxd(modelpath, mxdpath, filename, jpgpath, layerpath):
    mxd = arcpy.mapping.MapDocument(modelpath)
    if (os.path.exists(mxdpath)):
        mxd = arcpy.mapping.MapDocument(mxdpath)
        print("location as " + mxdpath)
        arcpy.AddWarning("该文件已经存在")
    else:
        mxd.saveACopy(mxdpath)
        print(mxdpath + " saveAs succefssful")
        if (os.path.exists(mxdpath)):
            mxd = arcpy.mapping.MapDocument(mxdpath)
            print("location in " + mxdpath)
    # 查找数据框
    df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
    # 增加底图
    #symbologyLayer = "D:\\cs\\model\\lyr\\Rectangle_#1_常熟卫图_Level_16.tif.lyr"
    #"F:\\xinxiang\\fil\\20190817mydPM25.tif"
    shpLayer = arcpy.mapping.Layer(filename)
    if (layerpath == "nonelayer"):
        pass
    else:
        sourceLayer = arcpy.mapping.Layer(layerpath)
        arcpy.mapping.UpdateLayer(df, shpLayer, sourceLayer, True)
    arcpy.mapping.AddLayer(df, shpLayer, "TOP")
    df.extent = shpLayer.getExtent()
    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()
    mxd.save()
    arcpy.mapping.ExportToJPEG(mxd, jpgpath, resolution=res)
Esempio n. 14
0
    def onClick(self):
        sourceLayer = arcpy.mapping.Layer(
            r"P:\Projects\__ArcMap_Master_GDB_LYR\CIR.lyr")
        mxd = arcpy.mapping.MapDocument("Current")
        df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
        targetGroupLayer = arcpy.mapping.ListLayers(mxd, "TIF_Group", df)[0]

        text_file = open("C:/timer_tiles/tile_list.txt", "r")
        lines = text_file.readlines()
        text_file.close()

        for i in range(0, len(lines)):

            newlayer = arcpy.mapping.Layer(lines[i])
            arcpy.mapping.UpdateLayer(df,
                                      newlayer,
                                      sourceLayer,
                                      symbology_only=True)
            arcpy.mapping.AddLayer(df, newlayer, "Bottom")
            del newlayer

        ext = targetGroupLayer.getExtent()
        df.extent = ext

        arcpy.RefreshActiveView()
        arcpy.RefreshTOC()

        del mxd, df
Esempio n. 15
0
def export_to_png(shp, output_dir):
    mxd = arcpy.mapping.MapDocument(join(output_dir, 'test.mxd'))
    df = arcpy.mapping.ListDataFrames(mxd, '*')[0]
    shp_layer = arcpy.mapping.Layer(shp)
    arcpy.mapping.AddLayer(df, shp_layer, 'BOTTOM')
    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()
def AddLayerToMap(addLayer):
    mxd = arcpy.mapping.MapDocument("CURRENT")
    df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
    arcpy.mapping.AddLayer(df, addLayer, "TOP")
    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()
    del mxd, df, addLayer
Esempio n. 17
0
def addToDisplay(filepath, level='BOTTOM'):
    mxd = arcpy.mapping.MapDocument('CURRENT')
    df = arcpy.mapping.ListDataFrames(mxd, 'Layers')[0]
    layer = arcpy.mapping.Layer(filepath)
    arcpy.mapping.AddLayer(df, layer, level)
    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()
Esempio n. 18
0
def make_map(dir):
    prev_workspace = arcpy.env.workspace
    arcpy.env.workspace = dir
    #Make a Map Document
    try:
        mapList = arcpy.ListFiles("*.mxd")
        mxd_path = os.path.join(dir, mapList[0])

        mxd = arcpy.mapping.MapDocument(mxd_path)
        data_frames = arcpy.mapping.ListDataFrames(mxd)
        data_frame = data_frames[0]
        fcs = arcpy.ListFeatureClasses()

        for f in fcs:
            out_layer = f[:-4]
            out_layer_file = out_layer + ".lyr"
            arcpy.MakeFeatureLayer_management(f, out_layer)
            arcpy.SaveToLayerFile_management(out_layer, out_layer_file)
            layer_object = arcpy.mapping.Layer(f)
            arcpy.mapping.AddLayer(data_frame, layer_object)

        arcpy.RefreshTOC()
        project_map = map_document[:-4] + "Presentation.mxd"
        mxd.saveACopy(os.path.join(prev_workspace, project_map))
        os.startfile(os.path.join(prev_workspace, project_map))
        arcpy.env.workspace = prev_workspace
        del mxd
    except arcpy.AddMessage("\tPlease check inputs"):
        arcpy.GetMessages()
Esempio n. 19
0
    def onClick(self):
        print "Nettoyage de la couche matricielle..."
        arcpy.Resample_management("classified raster", "resample", "0,3 0,3", "NEAREST")

        # Process: Boundary Clean
        arcpy.gp.BoundaryClean_sa("resample", "boundaryC", "NO_SORT", "TWO_WAY")

        # Process: Focal Statistics
        arcpy.gp.FocalStatistics_sa("boundaryC", "focalS", "Rectangle 6 6 CELL", "MAJORITY", "DATA")

        # Process: Focal Statistics (2)
        arcpy.gp.FocalStatistics_sa("focalS", "cleaned_raster", "Rectangle 6 6 CELL", "MAJORITY", "DATA")

        # Dé-sélection des couches inutiles
        selectedLayers = ["classified raster", "resample", "boundaryC", "focalS"]
        mxd = arcpy.mapping.MapDocument("current")
        df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
        layers = arcpy.mapping.ListLayers(mxd, "*", df)

        for layer in layers:
            if layer.name in selectedLayers:
                layer.visible = False

        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()
Esempio n. 20
0
 def show(self):
     '''show all available outputs (diagrams, layers etc.)'''
     self.show_layers()
     self.show_diagrams()
     self.show_images()
     arcpy.RefreshActiveView()
     arcpy.RefreshTOC()
Esempio n. 21
0
    def update_layersymbology(self, lyr, num_classes=13, column='weight'):
        """
        update the class break values of layersymbology

        Parameters
        ----------
        num_classes : int
            number of classes of the new layersymbology
        min_val : int or float
            minimum class value
        max_val : int or float
            maximum class value
        """
        from rpctools.utils.params import DummyTbx
        #get layer
        #mxd = arcpy.mapping.MapDocument('CURRENT')
        #lyr = arcpy.mapping.ListLayers(mxd, layername)
        #arcpy.AddMessage(lyr)
        #lyr = lyr[0]
        data_source = lyr.dataSource
        # get new classes
        tbx = DummyTbx()
        data = tbx._query_table(data_source, columns=[column])
        min_val = int(min(data)[0])
        max_val = int(max(data)[0]) + 1
        new_classes = np.linspace(min_val, max_val, num=num_classes + 1)
        new_classes = np.round(new_classes).astype(int)
        labels = ['bis zu {}'.format(c) for c in new_classes[1:]]
        # update layer
        lyr.symbology.classBreakValues = new_classes
        lyr.symbology.classBreakLabels = labels
        lyr.symbology.reclassify()
        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()
Esempio n. 22
0
    def mapSetElement(self, mxd, year, sheetnoText):
        # update map document with sheet numbers, orderID and address
        yearTextE = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT",
                                                     "MainTitleText")[0]
        yearTextE.text = str(year)

        mapsheetTextE = arcpy.mapping.ListLayoutElements(
            mxd, "TEXT_ELEMENT", "mapsheetText")[0]
        mapsheetTextE.text = "Map sheet(s): " + '\r\n' + sheetnoText

        orderIDTextE = arcpy.mapping.ListLayoutElements(
            mxd, "TEXT_ELEMENT", "ordernumText")[0]
        orderIDTextE.text = "Order No. " + self.order_obj.number

        AddressText = '%s %s %s %s' % (
            self.order_obj.address, self.order_obj.city,
            self.order_obj.province, self.order_obj.postal_code)
        AddressTextE = arcpy.mapping.ListLayoutElements(
            mxd, "TEXT_ELEMENT", "AddressText")[0]
        AddressTextE.text = "Address: " + AddressText + " "

        if self.is_newLogo == 'Y' and self.is_emg == 'N':
            logoE = arcpy.mapping.ListLayoutElements(mxd, "PICTURE_ELEMENT",
                                                     "logo")[0]
            logoE.sourceImage = os.path.join(cfg.logopath, self.newlogofile)

        arcpy.RefreshTOC()
 def create_map(xmxd):
     mxd = arcpy.mapping.MapDocument(xmxd)
     df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
     for lyr in arcpy.mapping.ListLayers(mxd, "", df):
         arcpy.mapping.RemoveLayer(df, lyr)
     arcpy.MakeFeatureLayer_management(datapath+"CA_County.shp", "County")
     arcpy.MakeFeatureLayer_management(newpath+"New_Solar.shp","Solar")
     arcpy.MakeFeatureLayer_management(newpath+"New_Wind.shp", "Wind")
     arcpy.MakeFeatureLayer_management(newpath+"New_Biomass.shp", "Biomass")
     arcpy.MakeFeatureLayer_management(newpath+"New_Geothermal.shp", "Geothermal")
     countylyr = arcpy.mapping.Layer("County")
     solarlyr = arcpy.mapping.Layer("Solar")
     windlyr = arcpy.mapping.Layer("Wind")
     biolyr = arcpy.mapping.Layer("Biomass")
     geolyr = arcpy.mapping.Layer("Geothermal")
     if xmxd != "CURRENT":
         legend = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "Legend")[0]
         legend.autoAdd = True
         elm = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT")
         elm[0].text = inputYear
         elm[1].text = scen
     arcpy.mapping.AddLayer(df,countylyr)    
     arcpy.mapping.AddLayer(df,solarlyr)
     arcpy.mapping.AddLayer(df,windlyr)
     arcpy.mapping.AddLayer(df,biolyr)
     arcpy.mapping.AddLayer(df,geolyr)
     arcpy.RefreshActiveView()
     arcpy.RefreshTOC()
     if xmxd != "CURRENT":
         legend.adjustColumnCount(1)
         mxd.save()
         arcpy.mapping.ExportToPDF(mxd, newpath+scen+"_"+inputYear+".pdf")
     del mxd
    def execute(self, parameters, messages):
        # This is the feature (table) name that we're working with.
        featureName = parameters[0].valueAsText
        featureRadius = parameters[2].valueAsText + " " + parameters[
            1].valueAsText
        featureDesc = arcpy.Describe(featureName)

        messages.addMessage("Feature Name: {0} Radius: {1}".format(
            featureName, featureRadius))

        # Add a Count column and default it to 1.
        # Not necessary, but kept here for reference.  The Join_Count field in the
        # "_sum" feature is used for this.
        #messages.addMessage("Adding field 'Count' to feature {0}".format(featureName))
        #arcpy.AddField_management(featureName, "Count", "SHORT")
        #arcpy.CalculateField_management(featureName, "Count", "1", "PYTHON_9.3")

        # Create a buffer around each point.
        bufferFeature = featureDesc.catalogPath + "_buffer"
        messages.addMessage("Adding buffer feature: {0}".format(bufferFeature))
        arcpy.Buffer_analysis(featureName, bufferFeature, featureRadius)

        # Join the collision data and the collision buffer.
        sumFeature = featureDesc.catalogPath + "_sum"
        messages.addMessage("Summarizing to {0}".format(sumFeature))
        arcpy.SpatialJoin_analysis(bufferFeature, featureName, sumFeature)

        # Show the feature layer.
        curMapDoc = arcpy.mapping.MapDocument("CURRENT")
        dataFrame = arcpy.mapping.ListDataFrames(curMapDoc, "Layers")[0]
        arcpy.mapping.AddLayer(dataFrame, arcpy.mapping.Layer(sumFeature),
                               "TOP")
        arcpy.RefreshTOC()

        return
Esempio n. 25
0
def show_things(thing_path, lyr_name, folder):

    gp = arcgisscripting.create()

    # Adding the layer to the table of contents
    mxd = arcpy.mapping.MapDocument("current")
    df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]

    file_type = arcpy.Describe(thing_path).dataType

    if file_type == u'RasterDataset':
        if not arcpy.Exists(thing_path):
            name_temp = os.path.join(folder, 'temp', '{}.tif'.format(os.path.split(thing_path)[-1]))
            arcpy.CopyRaster_management(thing_path, name_temp)
            arcpy.MakeRasterLayer_management(in_raster=name_temp, out_rasterlayer=lyr_name)
        else:
            arcpy.MakeRasterLayer_management(in_raster=thing_path, out_rasterlayer=lyr_name)
    elif (file_type == u'ShapeFile') or (file_type == u'FeatureClass'):
        if not arcpy.Exists(thing_path):
            name_temp = os.path.join(folder, 'temp', '{}.shp'.format(os.path.split(thing_path)[-1]))
            arcpy.CopyFeatures_management(thing_path, name_temp)
            arcpy.MakeFeatureLayer_management(in_features=name_temp, out_layer=lyr_name)
        else:
            arcpy.MakeFeatureLayer_management(in_features=thing_path, out_layer=lyr_name)
    else:
        gp.AddMessage('input file is not a raster or vector format')

    arcpy.SaveToLayerFile_management(lyr_name, os.path.join(folder, 'temp', '{}.lyr'.format(os.path.split(thing_path)[-1])), "ABSOLUTE")
    add_layer = arcpy.mapping.Layer(os.path.join(folder, 'temp', '{}.lyr'.format(os.path.split(thing_path)[-1])))
    arcpy.mapping.AddLayer(df, add_layer)
    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()
Esempio n. 26
0
    def run(self):
        """run HebesaetzeKontrolle Tool"""

        parameters = self.par
        projektname = self.par.name.value
        hebesatz = self.par.hebesatz.value
        target_gemeinde = self.par.gemeinde.value
        target_gemeinde_kurz = target_gemeinde.split(" ||")[0]
        basetable_GewSt = self.folders.get_base_table("FGDB_Basisdaten_deutschland.gdb", 'bkg_gemeinden')
        fields = ["GEN", "Hebesatz_GewSt"]
        for key in self.parent_tbx.gemeinden_dict:
            where_clause = '"GEN"' + "='" + key + "'"
            cursor = arcpy.da.UpdateCursor(basetable_GewSt, fields, where_clause)
            for gemeinde in cursor:
                gemeinde[1] = self.parent_tbx.gemeinden_dict[key]
                cursor.updateRow(gemeinde)

        mxd = arcpy.mapping.MapDocument("CURRENT")
        df = mxd.activeDataFrame
        if arcpy.mapping.ListLayers(mxd, projektname, df):
            projekt_layer = arcpy.mapping.ListLayers(mxd, projektname, df)[0]
            if arcpy.mapping.ListLayers(projekt_layer, "Gewerbesteuer"):
                lyr = arcpy.mapping.ListLayers(projekt_layer, "Gewerbesteuer")[0]
                lyr.symbology.reclassify()

            arcpy.RefreshActiveView()
            arcpy.RefreshTOC()
Esempio n. 27
0
 def onClick(self):
     inicio = time.time()
     mxd = arcpy.mapping.MapDocument('current')
     df = arcpy.mapping.ListDataFrames(mxd)[0]
     lyr = fc
     field_name = field
     coluna = field_name + "_Acum"
     dfp = gpd.read_file(lyr.workspacePath + "\\" + lyr.name + ".shp")
     dfp[coluna] = 0
     for index, row in dfp.iterrows():
         cobac = row.Pfaf
         cocur = row.cocurso
         dfp_sel = dfp.loc[operator.and_(dfp.Pfaf >= cobac,
                                         dfp.cocurso.str.startswith(cocur))]
         soma = dfp_sel[field_name].sum()
         dfp.loc[index, coluna] = soma
         del dfp_sel
     output = lyr.workspacePath + "\\" + lyr.name + "_Acum.shp"
     dfp.to_file(driver='ESRI Shapefile', filename=output)
     newlayer = arcpy.mapping.Layer(output)
     arcpy.mapping.AddLayer(df, newlayer, "AUTO_ARRANGE")
     arcpy.RefreshActiveView()
     arcpy.RefreshTOC()
     fim = time.time()
     tempo = fim - inicio
     pythonaddins.MessageBox(
         u'Tempo de execução: ' + "%.2f" % tempo + ' segundos', 'INFO', 0)
     pass
Esempio n. 28
0
def setOrdenLeyenda(mxd):
    leyenda = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")[0]
    leyenda.autoAdd = True

    Capa3 = arcpy.mapping.ListLayers(mxd, "zonificacion")[0]
    Capa1 = arcpy.mapping.ListLayers(mxd, "zona*")[0]
    try:
        Capa2 = arcpy.mapping.ListLayers(mxd, "Origen")[0]
    except:
        Capa2 = arcpy.mapping.ListLayers(mxd, "Destino*")[0]

    Capa1.name = "Zona de destino de los viajes"
    Capa2.name = "Numero Viajes"
    Capa3.name = "Capa3"

    arcpy.RefreshTOC()

    arcpy.mapping.AddLayer(df, Capa1, "TOP")
    arcpy.mapping.AddLayer(df, Capa2, "BOTTOM")
    arcpy.mapping.AddLayer(df, Capa3, "BOTTOM")

    Capa3.visible = False
    Capa2.visible = False
    Capa1.visible = False

    leyenda.autoAdd = True
Esempio n. 29
0
def createMxd(modelpath, mxdpath, symbologyLayer, jpgpath, string, lyrfile):
    mxd = arcpy.mapping.MapDocument(modelpath)
    if (os.path.exists(mxdpath)):
        mxd = arcpy.mapping.MapDocument(mxdpath)
        print("location as " + mxdpath)
        arcpy.AddWarning("该文件已经存在")
    else:
        mxd.saveACopy(mxdpath)
        print(mxdpath + " saveAs succefssful")
        if (os.path.exists(mxdpath)):
            mxd = arcpy.mapping.MapDocument(mxdpath)
            print("location in " + mxdpath)
    # 查找数据框
    df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
    # 增加底图
    #symbologyLayer = "D:\\cs\\model\\lyr\\Rectangle_#1_常熟卫图_Level_16.tif.lyr"
    #"F:\\xinxiang\\fil\\20190817mydPM25.tif"
    rasLayer = arcpy.mapping.Layer(lyrfile)
    arcpy.ApplySymbologyFromLayer_management(rasLayer, symbologyLayer)
    arcpy.mapping.AddLayer(df, rasLayer, "TOP")
    arcpy.AddMessage(str(time.ctime()) + ":" + symbologyLayer + "添加成功。。。")
    for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        if elm.text == u"20191013-05时":
            elm.text = string
    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()
    mxd.save()
    arcpy.mapping.ExportToJPEG(mxd, jpgpath, resolution=res)
Esempio n. 30
0
    def onMouseDownMap(self, x, y, button, shift):
        # make sure layer exists
        fc = "./endpoint.shp"
        if self.first:
            check(fc, 'endpoint.shp')
            self.first = False

        # check if point exists
        xy = (x, y)
        if int(arcpy.GetCount_management(fc).getOutput(0)) == 0:
            cursor = arcpy.da.InsertCursor(fc, ["SHAPE@XY"])
            cursor.insertRow([xy])
        else:
            cursor = arcpy.da.UpdateCursor(fc, ["SHAPE@XY"])
            for row in cursor:
                row[0] = xy
                cursor.updateRow(row)

        # find nearest road segment to point
        near_features = layer_combobox.value
        search_radius = "100 Meters"
        location = "NO_LOCATION"
        angle = "NO_ANGLE"
        arcpy.Near_analysis(fc, near_features, search_radius, location, angle)
        cursor = arcpy.da.SearchCursor(fc, ["NEAR_FID"])
        for row in cursor:
            if row[0] != -1:
                id = row[0]
            else:
                pythonaddins.MessageBox('Punkt za daleko od drogi', "Error")
                routing_type_combobox.value = ''
                routing_type_combobox.refresh()
                path_button_button.enabled = False
                return

        # snap point to nearest segment end
        exp = "FID = " + str(id)
        cursor = arcpy.da.SearchCursor(
            near_features, ["FID", 'START_X', 'START_Y', 'END_X', 'END_Y'],
            exp)
        for row in cursor:
            startx = float(row[1])
            starty = float(row[2])
            endx = float(row[3])
            endy = float(row[4])
            l1 = length(x, y, startx, starty)
            l2 = length(x, y, endx, endy)
            if l1 < l2:
                xy = (startx, starty)
            else:
                xy = (endx, endy)
            cursor = arcpy.da.UpdateCursor(fc, ["SHAPE@XY"])
            for row in cursor:
                row[0] = xy
                cursor.updateRow(row)
        # refresh view to see changes
        arcpy.RefreshActiveView()
        arcpy.RefreshTOC()
        routing_type_combobox.enabled = True