def onClick(self):
     #get the inputs (theoretically I'd like to loop though and find parent i,j automatically, but there's a variable # of domains and master regions)
     master_domain = pythonaddins.OpenDialog("Select your Master Domain", False, "", "","","")
     nest = pythonaddins.OpenDialog("Select your next Nested Domain", False, "", "","","")
     #calculate extents and get the lat/lon origin of the nested domain
     desc1 = ap.Describe(master_domain)
     desc2 = ap.Describe(nest)
     ext_master = desc1.extent
     ext_nested = desc2.extent
     if ext_master.contains(ext_nested) == True: #check if it actually fits
         nest_x = ext_nested.XMin
         nest_y = ext_nested.YMin
         x_y = "%s %s"%(nest_x, nest_y)
         #get cell value of MASTER at the point from nest 
         cell_val = float(ap.GetCellValue_management(master_domain, x_y, "")[0])
         #with cell value, find index on numpy array
         my_array = ap.RasterToNumPyArray(master_domain)
         index = numpy.where(my_array == cell_val)
         max_rows = int(ap.GetRasterProperties_management(master_domain, "ROWCOUNT", "")[0])
         print "rows complete"
         def index_to_namelist(sample_index, rows): #using the actual index instead of calculating it based on geographic distance 
             i = int(sample_index[1])+1
             y = int(sample_index[0])
             j = rows - y
             return i, j
         i_temp, j_temp = index_to_namelist(index, max_rows)
         global global_i, global_j
         global_i.append(i_temp)
         global_j.append(j_temp)            
         print "The current nest indexes are: \ni: %r \nj:%r\nKeep on going until all nests are added" %(global_i, global_j)
     else:
         pythonaddins.MessageBox("DOMAIN ERROR: Nested domain is not contained within the Master Domain","DOMAIN ERROR!", 5)
         print "Try again!" #message box should get this, but keeping things consistent
Beispiel #2
0
    def onClick(self):
        print "Choix d'un repertoire de travail, ainsi que l'image a classifier..."
        global wdPath
        wdPath = pythonaddins.OpenDialog("Selectionnez un repertoire de travail...", False, "C:", "Ajouter")
        print wdPath
        global rasterPath
        rasterPath = pythonaddins.OpenDialog("Selectionnez une couche matricielle...", False, "C:", "Ajouter")
        print rasterPath

        arcpy.MakeRasterLayer_management(rasterPath, "rasterLayer")
Beispiel #3
0
    def onClick(self):
        print
        genpolig.enabled = False
        gentopo.enabled = False
        nomdist.value = ''
        nomdist.refresh()

        self.ubi = pythonaddins.OpenDialog(nls().inicio().title, False, "#",
                                           nls().inicio().button, lambda x: x,
                                           "Feature Class")
        self.loc = unicode(self.ubi)
        evalue = os.path.basename(self.ubi).split('.')

        if len(evalue) == 1:

            if '.gdb' in self.loc:
                try:
                    nomdist.value = self.getName()
                    nomdist.refresh()
                    genpolig.enabled = True
                    pythonaddins.MessageBox(nls().succesfull, nls().title)
                except:
                    pythonaddins.MessageBox(nls().inicio().fielderror,
                                            nls().titleError)
                    loaddata.onClick()
            else:
                pythonaddins.MessageBox(nls().inicio().typeerror,
                                        nls().titleError)
                loaddata.onClick()
        else:
            pythonaddins.MessageBox(nls().inicio().typeerror, nls().titleError)
            loaddata.onClick()
Beispiel #4
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)
Beispiel #5
0
 def onClick(self):
     GenInfo.workpath = pythonaddins.OpenDialog('Select a folder')
     print GenInfo.workpath
     arcpy.env.workspace = GenInfo.workpath
     # Create a file geodatabase
     TD = 'TestTD.gdb'
     if not arcpy.Exists(TD):
         arcpy.CreateFileGDB_management(GenInfo.workpath, TD)
     # Create point and line feature classes
     self.spatial_reference = arcpy.Describe(
         GenInfo.list[1]).spatialReference
     GenInfo.sptialReferernce = self.spatial_reference
     if not arcpy.Exists('Point'):
         arcpy.CreateFeatureclass_management(TD, 'Point', 'POINT', "#", "#",
                                             "#", self.spatial_reference)
     if not arcpy.Exists('Line'):
         arcpy.CreateFeatureclass_management(TD, 'Line', 'POLYLINE', "#",
                                             "#", "#",
                                             self.spatial_reference)
         arcpy.AddField_management('Line', 'DeleteID', 'TEXT', '', '', '10')
     if not arcpy.Exists('Polygon'):
         arcpy.CreateFeatureclass_management(TD, 'Polygon', 'POLYGON', "#",
                                             "#", "#",
                                             self.spatial_reference)
     if not arcpy.Exists('Domain'):
         try:
             arcpy.CreateTable_management(TD, 'Domain')
             arcpy.AddField_management('Domain', 'URIDomain', 'TEXT', '',
                                       '', '200')
         except:
             print "domain has not been created"
Beispiel #6
0
    def onEditChange(self, text):
        Results.value = ''
        Results.refresh()
        global query
        query = text
        print(query)

        # Check to see if EAD layers are in mxd.
        mxd = arcpy.mapping.MapDocument("CURRENT")
        df = arcpy.mapping.ListDataFrames(mxd, "")[0]
        layer_list = arcpy.mapping.ListLayers(mxd, "EAD Facilities", df)
        print(layer_list)
        if len(layer_list) == 0:
            print("EAD Facilities not present")
            pythonaddins.MessageBox("'EAD Facilities' layer group must be added to map.", "Layers Present", 0)

            # Open the OpenDialog (add data) and create the objects list for use in Addlayer.
            ead_layer_file = pythonaddins.OpenDialog("Add 'EAD Facilities'",
                                                     "False",
                                                     r"PATH\TO\EAD\LAYERS",
                                                     "Open")
            print(ead_layer_file)
            for layer in ead_layer_file:
                # Create object for layer in list.
                ead_lyr = arcpy.mapping.Layer(layer)
                print(ead_lyr)
                # Add object to mxd.
                arcpy.mapping.AddLayer(df, ead_lyr)
                print("Layer added")

        else:
            print("EAD Facilities is present")
Beispiel #7
0
 def onClick(self):
     ubi = pythonaddins.OpenDialog(nls().ConfigGDB().title, False, "#",
                                   nls().ConfigGDB().namebutton,
                                   lambda x: x, "Geodatabase (GDB)")
     if ubi:
         evalue = os.path.basename(ubi).split(".")
         if len(evalue) >= 2:
             if evalue[-1] == 'gdb':
                 if os.path.exists(self.dirname):
                     pass
                 else:
                     os.mkdir(self.dirname)
                 fl = Conexion().path
                 data = {
                     'conn':
                     ubi,
                     'templates':
                     os.path.join(os.path.dirname(__file__), "templates")
                 }
                 self.createJson(fl, data)
                 self.connection = True
                 pythonaddins.MessageBox(nls().suscefull, nls().title)
             else:
                 pythonaddins.MessageBox(nls().ConfigGDB().error,
                                         nls().titleError)
                 self.onClick()
         else:
             pythonaddins.MessageBox(nls().ConfigGDB().error,
                                     nls().titleError)
             self.onClick()
     else:
         pass
Beispiel #8
0
 def onClick(self):
     global plik_z_krawedziami
     plik_z_krawedziami = pythonaddins.OpenDialog("Open", False, "")
     global plik_z_werteksami
     plik_z_werteksami = pythonaddins.SaveDialog(
         "Save", "werteksy.shp", "",
         lambda x: x and x.lower().endswith('.shp'), "Shapefile")
     lab1.wczytaj_dane(plik_z_krawedziami, plik_z_werteksami)
     global graf
     graf = lab2.stworz_graf(plik_z_werteksami, plik_z_krawedziami)
     tool1.enabled = True
Beispiel #9
0
 def onClick(self):
     layer_files = pythonaddins.OpenDialog('Select Layers to Add', True,
                                           r'C:\ArcpyBook\data\Wildfires',
                                           'Add')
     mxd = arcpy.mapping.MapDocument('current')
     df = pythonaddins.GetSelectedTOCLayerOrDataFrame()
     if not isinstance(df, arcpy.mapping.Layer):
         for layer_file in layer_files:
             layer = arcpy.mapping.Layer(layer_file)
             arcpy.mapping.AddLayer(df, layer)
     else:
         pythonaddins.MessageBox('Select a data frame', 'INFO', 0)
Beispiel #10
0
    def onClick(self):
        message1 = "Have you saved a text file report from the Check Fabric tool for the setup fabric?\n\n If yes, click OK and navigate to the location.\n\n If not, click Cancel. Please run the Check Fabric tool by right clicking on the parcel fabric. Next save the report as a text file."
        box1 = pythonaddins.MessageBox(message1, "Find Check Fabric Text File",
                                       1)
        if box1 == 'OK':
            textFile = pythonaddins.OpenDialog("Find Check Fabric Text File")
            #print textFile
            F1 = open(textFile, 'rb')
            parcelId1 = []
            for line in F1:
                if "Parcel with ID =" in line:
                    pID = line[17:-28]
                    parcelId1.append(pID)
            pfl = arcpy.mapping.ListLayers(mxd, "*Parcels")
            for layer in pfl:
                if layer.name == "Tax Parcels":
                    polygons = "FabricInvestigation\\Tax Parcels"
                elif layer.name == "Parcels":
                    polygons = "FabricInvestigation\\Parcels"
                else:
                    # Adding a message box here will cause tool to fail due to
                    # the looping of the layers when it finds layers not
                    # containing the Parcels or Tax Parcels.
                    pass
            for ID in parcelId1:
                if ID == parcelId1[0]:
                    where = '"OBJECTID" =' + str(ID)
                else:
                    where = where + 'OR "OBJECTID" = ' + str(ID)

            arcpy.SelectLayerByAttribute_management(polygons, "NEW_SELECTION",
                                                    where)

            box3 = pythonaddins.MessageBox(
                "Done selecting bad parcels. Click Yes if you would like to save as a feature class. Click No to return to map.",
                "Finished Process", 4)
            if box3 == "Yes":
                newFC = pythonaddins.SaveDialog("Save Bad Parcels")
                if newFC != "Cancel":
                    arcpy.CopyFeatures_management(polygons, newFC)
            else:
                pass
        newPath, newLayer = os.path.split(newFC)
        arcpy.mapping.MoveLayer(
            df,
            arcpy.mapping.ListLayers(mxd, "FabricInvestigation")[0],
            arcpy.mapping.ListLayers(mxd, newLayer)[0], "BEFORE")
        Parcel.checked = False
Beispiel #11
0
 def onClick(self):
     global parcelFabric, parcelFabricLayer, SR
     box = pythonaddins.MessageBox(
         "Navigate to the Parcel Fabric you wish to investigate.",
         "Select Parcel Fabric", 0)
     parcelFabric = pythonaddins.OpenDialog("Find Parcel Fabric")
     parcelFabricLayer = arcpy.MakeParcelFabricLayer_fabric(
         parcelFabric, "FabricInvestigation")
     SR = arcpy.Describe(parcelFabric).spatialReference
     Parcel.enabled = True
     Parcel.checked = True
     DupPoints.enabled = True
     DupPoints.checked = True
     Point.enabled = True
     Point.checked = True
     ParcelFabricSetup.checked = False
     ParcelLineGaps.enabled = True
     ParcelLineGaps.checked = True
 def onSelChange(self, selection):
     floder = pythonaddins.OpenDialog("please select a floder", False,
                                      r"D:\test", "Save")
     self.mxd = arcpy.mapping.MapDocument('current')
     layer = pythonaddins.GetSelectedTOCLayerOrDataFrame()
     if isinstance(layer, arcpy.mapping.Layer):
         #arcpy.MakeFeatureLayer_management(layer, "lyr")
         icursor = arcpy.SearchCursor(layer)
         for row in icursor:
             igetvalue = row.getValue(selection)
             print "selection:", selection
             print "igetvalue:", igetvalue
             print """ "%s" = '%s' """ % (selection, igetvalue)
             arcpy.SelectLayerByAttribute_management(
                 layer, "NEW_SELECTION",
                 """ "%s" = '%s' """ % (selection, igetvalue))
             save_name = igetvalue + ".shp"
             outsave = os.path.join(floder, save_name)
             arcpy.CopyFeatures_management(layer, outsave)
             arcpy.SelectLayerByAttribute_management(
                 layer, "CLEAR_SELECTION")
 def onClick(self):
     data_path = pythonaddins.OpenDialog("Select the location of your static data directory", False, "", "", "", "")
     self.geog_data_path = data_path
     print "geog_data_path = %s" %data_path #just to error check
 def onClick(self):
     #iterate through number of domains
     #note: select the nest and parent domain iteratively, starting with the original 'master'
     global domain_number
     counter = 0
     num = domain_number
     num = int(num)
     num_files = num-1
     #establish local var's
     e_we = [] 
     e_sn = []
     dx = 0
     dy = 0 
     parent_id = [1]
     parent_grid_ratio = [1] #done
     while counter < num_files:
         parent = pythonaddins.OpenDialog("Select the parent nest", False, "", "", "", "")
         nest = pythonaddins.OpenDialog("Select the nest", False, "", "", "", "")
         #ok, select values for the FIRST set (vars only needing one value)
         if counter == 0: 
             #cell res for original master
             dx = int(ap.GetRasterProperties_management(parent,"CELLSIZEX","")[0])
             dy = dx
             #domain geographic properties for the master (projected to geographic coordinates)
             scratch_raster = ap.ProjectRaster_management(parent, "in_memory\\scratch_raster", "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]", "NEAREST", "", "", "", "")
             obj = ap.Describe(scratch_raster)
             ext = obj.extent
             ref_lon = float((ext.XMax + ext.XMin)/2) #to find the mean point in the center of the raster in terms of lat/lon
             ref_lat = float((ext.YMax + ext.YMin)/2) 
             truelat1 = float(ext.YMin)
             truelat2 = float(ext.YMax)
             stand_lon = ref_lon
             ap.Delete_management(scratch_raster, "") #clean up the memory workspace
         else:
             pass #so moves on if counter > 0
         #now calculate parent_grid ratio (auto-start w/ 1 for master domain)
         res_parent = ap.GetRasterProperties_management(parent, "CELLSIZEX", "")[0]
         res_nest = ap.GetRasterProperties_management(nest, "CELLSIZEX","")[0]
         ratio = int(res_parent)/int(res_nest)
         parent_grid_ratio.append(ratio)
         temp_ratios = [float(i) for i in parent_grid_ratio]
         #parent_id (domain id of the parent, starting with 1)
         id = counter+1
         parent_id.append(id) 
         #calculate e_sn, e_we (num cells in x,y directions)
         #define function first
         def domain_adjust(numbers, ratios):
             for i, (x, y) in enumerate(zip(numbers, ratios)):
                 if i == 0:
                     numbers[i] = int(x)
                 else:
                     if x%y == 0.0:
                         numbers[i] = int(numbers[i]+1.0)
                     else:
                         numbers[i] = int((round(x/y)*y)+1.0)
             return numbers
         e_sn.append(float(ap.GetRasterProperties_management(parent, "ROWCOUNT", "")[0])) #so get the individual value (overwritten every iteration)
         e_we.append(float(ap.GetRasterProperties_management(parent,"COLUMNCOUNT", "")[0])) #same as above
         if counter == num_files-1: #to get the final cell count on the list, on the final repetition
             e_sn.append(float(ap.GetRasterProperties_management(nest, "ROWCOUNT","")[0]))
             e_we.append(float(ap.GetRasterProperties_management(nest, "COLUMNCOUNT","")[0]))
             #now everything's accounted for, we need to shift things up a bit
             e_sn = domain_adjust(e_sn, temp_ratios)
             e_we = domain_adjust(e_we, temp_ratios)
         #to end the loop
         counter+=1
     #######now, all values should be appended to the list, so you just need to write them out
     #first, convert them to strings ending in a comma, rather than list objects 
     parent_id = ",".join([str(x) for x in parent_id])
     parent_grid_ratio = ",".join([str(x) for x in parent_grid_ratio])
     global global_i, global_j #call the global variables.  Global b/c you're altering them to a string below, not just printing them out
     i_parent_start = global_i
     j_parent_start = global_j
     i_parent_start = ",".join([str(x) for x in i_parent_start])
     j_parent_start = ",".join([str(x) for x in j_parent_start])
     e_sn = ",".join([str(x) for x in e_sn])
     e_we = ",".join([str(x) for x in e_we])
     data_path = selectData.geog_data_path
     #and print everything out to finish
     print "Writing out namelist.wps in %s"%outPath.output_location
     namelist = "%s\\namelist.wps" %outPath.output_location
     output_namelist = open(namelist, 'w')
     output_namelist.write("&share\n")
     output_namelist.write("wrf_core = 'ARW',\n")
     output_namelist.write("max_dom = %r,\n" %domain_number) 
     output_namelist.write("io_form_geogrid = 2,\n") #requires netcdf files, but those are pretty default
     output_namelist.write("/\n\n")
     output_namelist.write("&geogrid\n")
     output_namelist.write("parent_id= %s,\n" %parent_id) 
     output_namelist.write("parent_grid_ratio = %s,\n" %parent_grid_ratio) 
     output_namelist.write("i_parent_start = %s,\n" %i_parent_start)
     output_namelist.write("j_parent_start = %s,\n" %j_parent_start)
     output_namelist.write("e_we = %s, \n" %e_we)
     output_namelist.write("e_sn = %s, \n" %e_sn)
     output_namelist.write("geog_data_res = '30s'\n") ########change to input var w/ easy combo box
     output_namelist.write("dx = %i,\n" %dx)
     output_namelist.write("dy= %i, \n" %dy)
     output_namelist.write("map_proj = 'lambert',\n")
     output_namelist.write("ref_lat = %.10f,\n" %ref_lat)
     output_namelist.write("ref_lon = %.10f,\n" %ref_lon) 
     output_namelist.write("truelat1 = %.10f,\n" %truelat1)
     output_namelist.write("truelat2 = %.10f,\n" %truelat2) 
     output_namelist.write("stand_lon = %.10f,\n" %stand_lon) 
     output_namelist.write("geog_data_path '%s'\n" %data_path) 
     output_namelist.write("/")
     output_namelist.close()
     print "Done!"
 def onClick(self):
     output_loc = pythonaddins.OpenDialog("Select the location of your output wrf-fire (wps) directory",False, "", "", "", "")
     self.output_location = output_loc
Beispiel #16
0
def readPath():
    try:
        return pa.OpenDialog(msgDict["OpenDialog"], False, "~/", "Open")
    except Exception as e:
        printErrorMessage(e)
        return None
Beispiel #17
0
    def onClick(self):
        #Ding Yi Chang Liang
        Ext = [".tif", ".pix", ".img"]
        ImgNameField = "NAME"

        #Ding Yi Kong ZiDian / LieBiao
        Image_Dic = {}
        ImagesAdd2Arcmap_List = []
        imageList = []

        #Ding Yi Hanshu
        def addImagesFromFolder(foderName):
            DOM_folders = os.path.join(BaseMapFolder, foderName)
            for rootdir, dirs, files in os.walk(DOM_folders):
                for file in files:
                    filepath = os.path.join(rootdir, file)
                    if os.path.splitext(filepath)[1] in Ext:
                        imageList.append(filepath)

        def GetEN_Time(L):
            E_pos = L.find("E")
            L_name = L[E_pos:]
            index = L_name.find("_")
            index2 = L_name.find("_", index + 1)
            index3 = L_name.find("_", index2 + 2)
            Name = L_name[:index3]
            return Name

        #Ding Yi mxd / df / Check_Box / BaseMap_Box
        mxd = arcpy.mapping.MapDocument("current")
        df = arcpy.mapping.ListDataFrames(mxd)[0]
        Check_Box = arcpy.mapping.ListLayers(mxd, '', df)[0]
        BaseMap_Box = arcpy.mapping.ListLayers(mxd, '', df)[1]

        #Ding Yi Wen Jian Jia
        BaseMapFolder = pythonaddins.OpenDialog("Please Select BaseMap Folder",
                                                False, r"D:\\", "Open")

        if BaseMapFolder == None:
            sys.exit()
        else:
            #Qiu Check_Box Yu BaseMap_Box de Kong Jian Xiang Jiao Guan Xi
            arcpy.SelectLayerByLocation_management(BaseMap_Box, "INTERSECT",
                                                   Check_Box, "",
                                                   "NEW_SELECTION")

            #Ba gongzuo kongjian li de suoyou yingxiang dou tianjia dao [imageList] liebiao li.
            arcpy.env.workspace = BaseMapFolder
            folders = arcpy.ListWorkspaces("*", "Folder")
            for folder in folders:
                foderName = os.path.basename(folder).encode('UTF-8')
                addImagesFromFolder(foderName)
            print "imageList length:", len(imageList)
            print "\n"

            #ba imageList liebiao zhuan cheng zidian,
            #zidian de KEY shi jingdu_weidu_shijain,
            #zidian de  VALUE shi yingxiang de mingcheng.
            for Image in imageList:
                print "Image:", Image
                Image_key = GetEN_Time(Image.encode('UTF-8'))
                print "Image_key:", Image_key
                Image_Dic[Image_key] = Image.encode('UTF-8')
            print "Image_Dic length:", len(Image_Dic)
            print "\n"

            #Duqu xuanzhong de yingxiangkuang de shuxingbiao "NAME" ziduan,
            #ruguo NAME zai zidian li ,ba yingxiang append dao [ImagesAdd2Arcmap_List] liebiao li ,
            #ruguo meiyou ,jiu pass
            iRows = arcpy.SearchCursor(BaseMap_Box)
            for row in iRows:
                row_name = row.getValue(ImgNameField).encode(
                    'UTF-8')  #E115D2_N24D6_20151016
                print "row_name:", row_name
                if row_name in Image_Dic:
                    Image_name = Image_Dic[row_name]
                    print "Image_name:", Image_name
                    ImagesAdd2Arcmap_List.append(Image_name)
                else:
                    pass
            print "ImagesAdd2Arcmap_List lenth:", len(ImagesAdd2Arcmap_List)
            print "\n"

            #ba ImagesAdd2Arcmap_List liebiao li de yingxiang yici jiazai dao arcmap li.
            for Image in ImagesAdd2Arcmap_List:
                add_layer = os.path.basename(Image) + "_BaseMap"
                print add_layer
                arcpy.MakeRasterLayer_management(Image, add_layer)
                del add_layer
            arcpy.RefreshTOC()
Beispiel #18
0
 def onClick(self):
     self.fcEje = pythonaddins.OpenDialog(nls().eje().title, False, "#",
                                          nls().eje().button, lambda x: x,
                                          "Feature Class")
     # pythonaddins.MessageBox(gentopo.fcEje, nls().titleError)
     self.runButton()
Beispiel #19
0
    def onClick(self):
        global main_path
        global folderName
        main_path = pythonaddins.OpenDialog("Please Select Vectors Folder",
                                            False, "", "OK")
        print "main_path:", main_path
        #name_txt = ''
        code_txt = ''
        moutain_txt = ''
        placename_txt = ''
        folderName = os.path.basename(main_path)
        print "folderName:", folderName
        #name_txt = folderName[:-10]
        code_txt = folderName[-10:]
        arcpy.env.workspace = main_path
        list_fc = arcpy.ListFeatureClasses()
        print "list_fc:", list_fc
        ras_list = arcpy.ListRasters()
        print "ras_list:", ras_list
        mxd = arcpy.mapping.MapDocument('current')
        df_list = arcpy.mapping.ListDataFrames(mxd)
        print "setting MapDocument DataSource"
        RAOLK = u''
        PlaceName = u''
        Town = u''
        Moutain = u''
        WaterBody = u''
        River = u''
        contour_B = u''
        contour = u''
        MapSheet = u''
        for fc in list_fc:
            print "fc:", fc
            if u"ROALK" in fc:
                RAOLK = fc
            elif u"PlaceName" in fc:
                PlaceName = fc
            elif u"Mountain" in fc:
                Moutain = fc
            elif u"WaterBody" in fc:
                WaterBody = fc
            elif u"River" in fc:
                River = fc
            elif u"contour_B" in fc:
                contour_B = fc
            elif u"contour" in fc and "_B" not in fc:
                contour = fc
            elif u"Town" in fc:
                Town = fc
            elif u"MapSheet" in fc:
                MapSheet = fc
        print "featurelayer is ready"

        def GetName(featureclass):
            cursor = arcpy.SearchCursor(featureclass)
            for row in cursor:
                if row.getValue("NAME") <> "" and len(
                        row.getValue("NAME")) <= 4:
                    return row.getValue("NAME")
                    break
                else:
                    continue

        for df in df_list:
            lyrlist = arcpy.mapping.ListLayers(mxd, '', df)
            for lyr in lyrlist:
                print lyr.name
                if lyr.name == u"道路" and RAOLK <> "":
                    lyr.replaceDataSource(main_path, "SHAPEFILE_WORKSPACE",
                                          RAOLK[:-4])
                    #UniqueValuesSymbology(lyr)
                    arcpy.ApplySymbologyFromLayer_management(
                        lyr,
                        os.path.join(os.path.dirname(mxd.filePath),
                                     "road.lyr"))

                elif lyr.name == u"地名" and PlaceName <> "":
                    lyr.replaceDataSource(main_path, "SHAPEFILE_WORKSPACE",
                                          PlaceName[:-4])
                    placename_txt = GetName(lyr)  ##########
                    lyr.showLabels = True
                elif lyr.name == u"乡镇" and Town <> "":
                    lyr.replaceDataSource(main_path, "SHAPEFILE_WORKSPACE",
                                          Town[:-4])
                    lyr.showLabels = True
                elif lyr.name == u"山" and Moutain <> "":
                    lyr.replaceDataSource(main_path, "SHAPEFILE_WORKSPACE",
                                          Moutain[:-4])
                    moutain_txt = GetName(lyr)  #########
                    lyr.showLabels = True
                elif lyr.name == u"水体" and WaterBody <> "":
                    lyr.replaceDataSource(main_path, "SHAPEFILE_WORKSPACE",
                                          WaterBody[:-4])

                elif lyr.name == u"单线河" and River <> "":
                    lyr.replaceDataSource(main_path, "SHAPEFILE_WORKSPACE",
                                          River[:-4])

                elif lyr.name == u"等高线计曲线" and contour_B <> "":
                    lyr.replaceDataSource(main_path, "SHAPEFILE_WORKSPACE",
                                          contour_B[:-4])
                    lyr.showLabels = True
                elif lyr.name == u"等高线" and contour <> "":
                    lyr.replaceDataSource(main_path, "SHAPEFILE_WORKSPACE",
                                          contour[:-4])

                elif lyr.name == u"contour_Anno" or lyr.name == u"Town_Anno" or lyr.name == u"PlaceName_Anno" or lyr.name == u"Mountain_Anno" or lyr.name == u"Default":
                    continue

                elif lyr.name == u"影像":
                    lyr.replaceDataSource(main_path, "RASTER_WORKSPACE",
                                          ras_list[0])

                elif lyr.name == u"MapSheet":
                    lyr.replaceDataSource(main_path, "SHAPEFILE_WORKSPACE",
                                          MapSheet[:-4])
                    lyr.showLabels = True
                else:
                    lyr.visible = False
            arcpy.RefreshTOC()
            arcpy.RefreshActiveView()

            #设置dataframe的投影,将影像的投影信息赋给dataframe
            Spatial_ref = arcpy.Describe(contour).spatialReference
            #print "Spatial_ref:",Spatial_ref
            df_list[0].spatialReference = Spatial_ref
            #print "dataframe ref:",df_list[0].spatialReference
            arcpy.RefreshTOC()
            arcpy.RefreshActiveView()

        lyrlist0 = arcpy.mapping.ListLayers(mxd, '', df_list[0])
        for lyr0 in lyrlist0:
            if lyr0.name == u"影像":
                df_esxtent1 = lyr0.getExtent()
        df_list[0].panToExtent(df_esxtent1)
        df_list[0].scale = 20000
        arcpy.RefreshActiveView()

        lyrlist1 = arcpy.mapping.ListLayers(mxd, '', df_list[1])
        for lyr1 in lyrlist1:
            if lyr1.name == u"MapSheet":
                df_esxtent2 = lyr1.getExtent()
        df_list[1].extent = df_esxtent2
        df_list[1].scale = df_list[1].scale * 0.6
        arcpy.RefreshActiveView()

        ###########
        print "setting PageLayout properties"
        elm_txts = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT")
        print "placename_txt:", placename_txt
        print "placename_txt_length:", len(placename_txt)
        elm_txts[1].text = placename_txt
        print "elm_txts[1]:", elm_txts[1]
        elm_txts[0].text = moutain_txt
        elm_txts[7].text = code_txt
        #elm_txts[8].text = name_txt
        arcpy.RefreshActiveView()

        #print "setting txt_elem position"
        #item_count = 0
        #legend = arcpy.mapping.ListLayoutElements( mxd, "LEGEND_ELEMENT")
        #leg = legend[0]
        #item_count = len(leg.items)
        #height = leg.elementHeight
        #if "" in leg.items:
        #    item_count += 3
        #placeName_index = 0
        #if u"地名" in leg.items:
        #    placeName_index = leg.items.index(u"地名")
        #    elm_txts[1].elementPositionY = (9 - placeName_index) * height/10
        #if u"山" in leg.items:
        #    placeName_index = leg.items.index(u"山")
        #    elm_txts[2].elementPositionY = (9 - placeName_index) * height/10

        mxd.saveACopy(os.path.join(main_path, folderName + "layout.mxd"))
        pythonaddins.MessageBox("Data update ok!", "INFO", 0)
        pythonaddins.MessageBox(u"请修改图幅名称、图例!", "INFO", 0)