Ejemplo n.º 1
0
def addGHSL(urbanLayer, curMap, ghslFolder, datamaskFolder, lyrSymbology,
            extentsSymbology, ghslOutline):
    inputGHSLMap = r"S:\GLOBAL\Global_Human_Settlement_Layer\GHSL_Footprint_Maps.mxd"
    outlinesFL = "GHSLOut2"
    shapeFL = "InShape"
    arcpy.MakeFeatureLayer_management(ghslOutline, outlinesFL)

    #Open map and add urban layer
    mxd = arcpy.mapping.MapDocument(inputGHSLMap)
    mxd.saveACopy(curMap)
    mxd = arcpy.mapping.MapDocument(curMap)
    df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
    urbLyr = arcpy.mapping.Layer(urbanLayer)
    urbLyr.definitionQuery = 'NOT  "ExtentName" = \'0\''
    arcpy.ApplySymbologyFromLayer_management(urbLyr, extentsSymbology)
    arcpy.mapping.AddLayer(df, urbLyr)

    #Find intersecting
    curTitles = selectGHSLtiles(urbanLayer, ghslOutline, 'Path', False)

    lyrCnt = 0

    for c in curTitles:
        c = os.path.join(ghslFolder, c)
        #Add MT layer
        outLayer = "%s_%s" % (os.path.basename(c), "mt")
        #if not outLayer in [l.name for l in arcpy.mapping.ListLayers(mxd)]:
        result = arcpy.MakeRasterLayer_management(c, outLayer)
        layer = result.getOutput(0)
        arcpy.ApplySymbologyFromLayer_management(layer, lyrSymbology)
        arcpy.mapping.AddLayer(df, layer)

    df.extent = arcpy.Describe(urbanLayer).extent
    mxd.save()
Ejemplo n.º 2
0
def addGUF(gufMap, curTiles, urbanLayer, curMap, gufFolder, gufSymbology,
           extentsSymbology):
    outlinesFL = "GHSLOut2"
    shapeFL = "InShape"

    #Open map and add urban layer
    mxd = arcpy.mapping.MapDocument(gufMap)
    mxd.saveACopy(curMap)
    mxd = arcpy.mapping.MapDocument(curMap)
    df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
    urbLyr = arcpy.mapping.Layer(urbanLayer)
    urbLyr.definitionQuery = 'NOT  "ExtentName" = \'0\''
    arcpy.ApplySymbologyFromLayer_management(urbLyr, extentsSymbology)
    arcpy.mapping.AddLayer(df, urbLyr)

    lyrCnt = 0
    for c in curTiles:
        c = os.path.join(gufFolder, c)
        outLayer = "GHSL_%s" % lyrCnt
        #if not outLayer in [l.name for l in arcpy.mapping.ListLayers(mxd)]:
        result = arcpy.MakeRasterLayer_management(c, outLayer)
        layer = result.getOutput(0)
        arcpy.ApplySymbologyFromLayer_management(layer, gufSymbology)
        arcpy.mapping.AddLayer(df, layer)
        lyrCnt = lyrCnt + 1
    df.extent = arcpy.Describe(urbanLayer).extent
    mxd.save()
Ejemplo n.º 3
0
def mapPop(inMap, outMap, hdGrid, urbGrid, hdStyle, urbStyle, extents,
           extentsSymbology):
    mxd = arcpy.mapping.MapDocument(inMap)
    mxd.saveACopy(outMap)
    mxd = arcpy.mapping.MapDocument(outMap)
    df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]

    #Add the urban grid to the map
    result = arcpy.MakeRasterLayer_management(urbGrid)
    urbLyr = result.getOutput(0)
    arcpy.ApplySymbologyFromLayer_management(urbLyr, urbStyle)
    arcpy.mapping.AddLayer(df, urbLyr)

    #Add the high density urban grid to the map
    resultHD = arcpy.MakeRasterLayer_management(hdGrid)
    hdLyr = resultHD.getOutput(0)
    arcpy.ApplySymbologyFromLayer_management(hdLyr, hdStyle)
    arcpy.mapping.AddLayer(df, hdLyr)

    #Add the extents to the map
    extentLyr = arcpy.mapping.Layer(extents)
    extentLyr.definitionQuery = 'NOT  "ExtentName" = \'0\''
    arcpy.ApplySymbologyFromLayer_management(extentLyr, extentsSymbology)
    arcpy.mapping.AddLayer(df, extentLyr)

    mxd.save()
Ejemplo n.º 4
0
def main():
    mxd = arcpy.mapping.MapDocument("CURRENT")
    df = mxd.activeDataFrame

    # Get parameters from Arc
    geofile = arcpy.GetParameterAsText(0)
    xs_shape_file = arcpy.GetParameterAsText(1)
    xs_id_field = arcpy.GetParameterAsText(2)
    river_field = arcpy.GetParameterAsText(3)
    reach_field = arcpy.GetParameterAsText(4)
    out_dir = arcpy.GetParameterAsText(5)
    out_prefix = arcpy.GetParameterAsText(6)

    # Grab model name from RAS geometry file or use supplied name for shapefiles
    if out_prefix == '':
        geo_name = geofile.split('\\')[-1][:-4]
    else:
        geo_name = out_prefix

    if not os.path.exists(out_dir):
        os.mkdir(out_dir)

    arcpy.AddMessage('\n' + '*' * 20 + ' Creating N-value review lines... ')
    outfile = os.path.join(out_dir, geo_name + '_n_value.shp')
    file_check(outfile)
    n_value_review.n_value_review(geofile, xs_shape_file, xs_id_field,
                                  river_field, reach_field, outfile)
    new_layer = arcpy.mapping.Layer(outfile)
    arcpy.ApplySymbologyFromLayer_management(new_layer, N_VALUE_STYLE)

    # Set labels
    new_layer.showLabels = True
    for label_class in new_layer.labelClasses:
        label_class.expression = '"<ITA><FNT size=\'11\'>"&[Mannings_n]&"</FNT></ITA>"'
    arcpy.mapping.AddLayer(df, new_layer, "AUTO_ARRANGE")

    arcpy.AddMessage('\n' + '*' * 20 + ' Creating IEFA review lines... ')
    outfile = os.path.join(out_dir, geo_name + '_iefa.shp')
    file_check(outfile)
    iefa_review.iefa_review(geofile, xs_shape_file, xs_id_field, river_field,
                            reach_field, outfile)
    new_layer = arcpy.mapping.Layer(outfile)
    arcpy.ApplySymbologyFromLayer_management(new_layer, IEFA_STYLE)
    arcpy.mapping.AddLayer(df, new_layer, "AUTO_ARRANGE")

    arcpy.AddMessage('\n' + '*' * 20 +
                     ' Creating obstruction review lines... ')
    outfile = os.path.join(out_dir, geo_name + '_blocked.shp')
    file_check(outfile)
    blocked_review.obstruction_review(geofile, xs_shape_file, xs_id_field,
                                      river_field, reach_field, outfile)
    new_layer = arcpy.mapping.Layer(outfile)
    arcpy.ApplySymbologyFromLayer_management(new_layer, OBSTRUCTION_STYLE)
    arcpy.mapping.AddLayer(df, new_layer, "AUTO_ARRANGE")

    arcpy.RefreshTOC()
    arcpy.RefreshActiveView()
Ejemplo n.º 5
0
def ZonalHist(rasterLocation, raster, outpath_final, infc, FullFile):
    dem = rasterLocation + os.sep + str(raster)
    path, fc = os.path.split(infc)
    out = outpath_final
    arcpy.env.overwriteOutput = True
    start_loop = datetime.datetime.now()
    arcpy.MakeFeatureLayer_management(infc, "fc_lyr")
    if FullFile:
        runID = fc
        dbf = outpath_final + os.sep + str(runID)
        print dbf
        arcpy.MakeRasterLayer_management(dem, "rdlayer")
        symbologyLayer = "J:\Workspace\ESA_Species\Step3\ZonalHis_GAP\GAP.lyr"
        arcpy.ApplySymbologyFromLayer_management("rdlayer", symbologyLayer)
        codezone = functions.ZonalHist("fc_lyr", zoneField, "rdlayer", dbf,
                                       outpath_final)
        print "Full region completed in: {0}".format(datetime.datetime.now() -
                                                     start_loop)
    else:
        for row in arcpy.da.SearchCursor("fc_lyr", [zoneField, "SHAPE@"]):
            entid = row[0]
            #whereclause = "EntityID = '%s'" % (id)
            whereclause = "\"OBJECTID\"=" + str(
                entid)  #TODO Make this dyanmic to zon field
            lyr = "lyr"
            arcpy.MakeFeatureLayer_management("fc_lyr", lyr, whereclause)
            runID = str(raster[:-4]) + "_" + str(entid)
            print runID
            extent = row[1].extent
            Xmin = extent.XMin
            Ymin = extent.YMin
            Xmax = extent.XMax
            Ymax = extent.YMax
            extent_layer = str(Xmin) + " " + str(Ymin) + " " + str(
                Xmax) + " " + str(Ymax)
            dbf = outpath_final + os.sep + str(runID)
            print dbf
            if arcpy.Exists(dbf):
                continue
            else:
                arcpy.env.extent = extent_layer
                print extent_layer
                arcpy.MakeRasterLayer_management(dem, "rdlayer")
                symbologyLayer = "J:\Workspace\ESA_Species\Step3\ZonalHis_GAP\GAP.lyr"
                arcpy.ApplySymbologyFromLayer_management(
                    "rdlayer", symbologyLayer)
                functions.ZonalHist(lyr, zoneField, "rdlayer", dbf,
                                    outpath_final, scratchpath)
                del lyr

                print "Loop completed in: {0}".format(datetime.datetime.now() -
                                                      start_loop)
Ejemplo n.º 6
0
def makeLayerPackage(outputDataPath, pointLayer, upstreamLayer,
                     downstreamLayer, streamNetwork, demLayer,
                     streamNetworkOrig):
    """
    Applies symbology to layer files
    :param outputDataPath: What output folder we're in
    :param pointLayer: The layer points output
    :param upstreamLayer: The layer of upstream impact probabilities
    :param downstreamLayer: The layer of downstream impact probabilities
    :param streamNetwork: The stream network in the project folder
    :param demLayer: The DEM layer we made earlier
    :param streamNetworkOrig: The stream network file in the inputs folder
    :return: None
    """
    #TODO Make a layer package?
    projectPath = os.path.dirname(os.path.dirname(outputDataPath))
    tribCodeFolder = os.path.dirname(os.path.abspath(__file__))
    symbologyFolder = os.path.join(tribCodeFolder, 'symbology')
    pointSymbology = os.path.join(symbologyFolder, "TribImpactPoints.lyr")
    upstreamSymbology = os.path.join(symbologyFolder, "TribImpactUpstream.lyr")
    downstreamSymbology = os.path.join(symbologyFolder,
                                       "TribImpactDownstream.lyr")

    arcpy.ApplySymbologyFromLayer_management(pointLayer, pointSymbology)
    arcpy.SaveToLayerFile_management(pointLayer, pointLayer)

    arcpy.ApplySymbologyFromLayer_management(upstreamLayer, upstreamSymbology)
    arcpy.SaveToLayerFile_management(upstreamLayer, upstreamLayer)

    arcpy.ApplySymbologyFromLayer_management(downstreamLayer,
                                             downstreamSymbology)
    arcpy.SaveToLayerFile_management(downstreamLayer, downstreamLayer)

    streamNetworkLayer = streamNetworkOrig[:-4] + '.lyr'
    arcpy.MakeFeatureLayer_management(streamNetworkOrig, streamNetworkLayer)
    arcpy.SaveToLayerFile_management(streamNetworkLayer, streamNetworkLayer)

    layerPackageFolder = makeFolder(outputDataPath, "03_LayerPackage")
    layerPackage = os.path.join(layerPackageFolder, "layerPackage.lpkx")
    layers = [
        pointLayer, upstreamLayer, downstreamLayer, demLayer,
        streamNetworkLayer
    ]

    try:
        arcpy.PackageLayer_management(layers, layerPackage)
    except:
        arcpy.AddWarning(
            'We could not package the output into a single layer package. This is often a result of a '
            +
            'known bug in ArcGIS 10.6. You may try packaging the outputs together yourself if you wish'
        )
Ejemplo n.º 7
0
def make_layers(huc_shp, symbologyList, nameList, outputFolder):
    # Creates all necessary layers, given a list of symbology filepaths and names for the files

    # Initialize Variables
    layerPathList = []

    # Create every layer
    for symbology, name in zip(symbologyList, nameList):
        print "\nCreating Layer: " + name + "...\n"
        # Make a new layer with a name from the nameList
        newLayer = arcpy.MakeFeatureLayer_management(huc_shp, name)
        # Apply appropriate symbology from the symbology List
        arcpy.ApplySymbologyFromLayer_management(newLayer, symbology)
        # Create a filepath to save the layer
        filePath = clean_filepath(os.path.join(outputFolder, (name + "_Summary.lyr")))
        # Check to see if the layer we are looking at is the reference labels file, as that has special considerations
        if symbology == os.path.join(symbology_folder, "Summary_Labels.lyr"):
            temp = symbolize_labels(newLayer, filePath, symbology, outputFolder)
            newLayer = temp
        # Save the layer
        arcpy.SaveToLayerFile_management(newLayer, filePath)
        # Add this filepath to a list. This will be used to create the layer package
        layerPathList.append(filePath)

    return layerPathList
Ejemplo n.º 8
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()
Ejemplo n.º 9
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)
            # rasLayer.symbology.
            arcpy.ApplySymbologyFromLayer_management (rasLayer,symbologyLayer)
            arcpy.mapping.AddLayer(df, rasLayer, "AUTO_ARRANGE")
            elmlist=arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT")
            legendlist = arcpy.mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")
            for legend in legendlist:
                print(legend)
            for 
            
            
            
            
            
            elm in elmlist:
                print(elm.text)
            mxd.save()
    arcpy.mapping.ExportToJPEG(mxd, jpgpath, resolution = res)
Ejemplo n.º 10
0
def geometriaScr(scr, sql, SEGM_R_AER, df, SCR_LYR, mxd):

    nameSCR = 'SCRmfl'

    SCRmfl_TMP = arcpy.MakeFeatureLayer_management(SEGM_R_AER, "SCRmfl_TMP",
                                                   sql)
    SCRdisolve = arcpy.Dissolve_management(SCRmfl_TMP, 'in_memory\seccion',
                                           '#', '#', 'MULTI_PART',
                                           'DISSOLVE_LINES')
    mfl = arcpy.MakeFeatureLayer_management(SCRdisolve, nameSCR)
    arcpy.AddField_management(mfl, "SCR", "TEXT", '#', '#', '3')
    with arcpy.da.UpdateCursor(mfl, ["SCR"]) as cursorUC:
        for row in cursorUC:
            row[0] = str(scr).zfill(3)
            cursorUC.updateRow(row)
    del cursorUC

    layerFileSCR = arcpy.mapping.Layer(nameSCR)
    arcpy.RefreshActiveView()
    arcpy.ApplySymbologyFromLayer_management(layerFileSCR, SCR_LYR)
    arcpy.RefreshActiveView()
    arcpy.mapping.AddLayer(df, layerFileSCR)
    arcpy.RefreshActiveView()

    for x in arcpy.mapping.ListLayers(mxd):
        if x.name == 'SCRmfl':
            arcpy.RefreshActiveView()
            lblclass = x.labelClasses[0]
            arcpy.RefreshActiveView()
            lblclass.expression = '''"<FNT size = '20'>" & "<CLR red='0' green='0' blue='0'>" & "<BOL>" & "SCR: " & [SCR] & "</BOL>" & "</CLR>" & "</FNT>"'''
            x.showLabels = True
            arcpy.RefreshActiveView()
Ejemplo n.º 11
0
def call_zonal_hist(sp_file, zone, use_r, outtable, symbologyLayer, snap_raster, scratchpath, outpath_final,sp_group,use):
    print ("Running Statistics...for species group {0} and raster {1}".format(sp_group, use))
    arcpy.env.scratchWorkspace = scratchpath
    arcpy.env.workspace = outpath_final

    arcpy.CheckOutExtension("Spatial")
    snap_raster = Raster(snap_raster)
    snap ="snap"

    arcpy.MakeRasterLayer_management(snap_raster, snap)
    arcpy.env.snapRaster = snap_raster
    arcpy.MakeRasterLayer_management(use_r, "raster_lyr", "#", snap, '#')
    symbology_layer = symbologyLayer
    arcpy.ApplySymbologyFromLayer_management("raster_lyr", symbology_layer)

    arcpy.MakeRasterLayer_management(sp_file, "sp_lyr")
    try:

        arcpy.gp.ZonalHistogram_sa("sp_lyr", zone, "raster_lyr", outtable)

        print 'Final file can be found at {0}'.format(outtable)



    except Exception as error:
        print 'Error in loop'
        print(error.args[0])

    del snap
Ejemplo n.º 12
0
def feature_paa_kart(fgdb, fc):
    symbologyLayer = "C:/Users/jan.aalbu/Documents/Koding/alfabeta/Alfa-beta_punkter.lyrx"
    data = fgdb + "\\" + fc
    aprx = arcpy.mp.ArcGISProject("CURRENT")
    aprxMap = aprx.listMaps(aprx.activeMap.name)[0]
    aprxMap.addDataFromPath(data)
    arcpy.ApplySymbologyFromLayer_management(data, symbologyLayer)
Ejemplo n.º 13
0
def idw():
    #Setting up the workspace
    arcpy.env.workspace = "C:\\MAMP\\htdocs\\cancerAnalysis\\files\\well_nitrate"
    arcpy.env.overwriteOutput = True
    arcpy.CheckOutExtension("Spatial")
    # status["text"] = "Running IDW..."

    #Setting up the variables
    inPoint = "well_nitrate.shp"
    zField = "nitr_ran"
    power = float(powerEntry.get())
    print power
    searchRadius = RadiusVariable(10, 150000)

    #Run IDW
    idwOutPut = Idw(inPoint, zField, "", power, searchRadius)

    #Save the output raster
    idwOutPut.save("C:\\MAMP\\htdocs\\cancerAnalysis\\project1\\idw.tif")

    #Update the mxd to include the IDW raster
    mxd = arcpy.mapping.MapDocument(r"C:\\MAMP\\htdocs\\cancerAnalysis\\idwMap.mxd")
    dataFrame = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]

    #Change the symbology of the IDW raster
    idwTiff = arcpy.mapping.Layer(r"C:\\MAMP\\htdocs\\cancerAnalysis\\project1\\idw.tif")
    idwSymbology = r"C:\\MAMP\\htdocs\\cancerAnalysis\\project1\\idwSymbology.lyr"
    arcpy.ApplySymbologyFromLayer_management(idwTiff, idwSymbology)

    #Add newly changed IDW raster to the map
    arcpy.mapping.AddLayer(dataFrame, idwTiff, "BOTTOM")

    #Export the map
    arcpy.mapping.ExportToPNG(mxd, "C:\\MAMP\\htdocs\\cancerAnalysis\\idwResults.png")
Ejemplo n.º 14
0
def make_map(dl_dir, rootpath, schools_buff_loc, schools_file_full_loc,\
             schools_layer_loc, neighborhoods_loc):
    """create our map using the arc mapping module
    returns nothing
    """
    #set up basic arc options
    arcpy.env.workspace = newpath
    arcpy.env.overwriteOutput = True
    #initial mxd template we use
    mxd_path = os.path.join(os.getcwd(), "final.mxd")
    #name of PDF map we create
    output_pdf_name = "Healthy_Stores_per_School.pdf"
    
    #set up mxd object and data frames
    mxd = arcpy.mapping.MapDocument(mxd_path)
    data_frames = arcpy.mapping.ListDataFrames(mxd)
    data_frame = data_frames[0]

    #create layers from the neighborhood and schools shape files 
    layer0 = arcpy.mapping.Layer(neighborhoods_loc)
    layer1 = arcpy.mapping.Layer(schools_file_full_loc)
    #copy the symbology from the downloaded .lyr file. this is an inelegant
    #way to accomplish this, but here we are
    #this file was manually created in arcmap beforehand
    arcpy.ApplySymbologyFromLayer_management(layer1, schools_layer_loc)
    #add both layers into the map document we're about to export.
    #make sure the base layer is on the bottom
    arcpy.mapping.AddLayer(data_frame, layer0, "BOTTOM")
    arcpy.mapping.AddLayer(data_frame, layer1, "TOP")
    
    #export to PDF
    arcpy.mapping.ExportToPDF(mxd, os.path.join(rootpath, output_pdf_name))
    #also save out the modified mxd document for some manual prettying up
    mxd.saveACopy(os.path.join(rootpath, "Healthy_Stores_per_School.mxd"))
Ejemplo n.º 15
0
def makeLayer(output_folder,
              layer_base,
              new_layer_name,
              symbology_layer,
              isRaster,
              description="Made Up Description"):
    """
    Creates a layer and applies a symbology to it
    :param output_folder: Where we want to put the folder
    :param layer_base: What we should base the layer off of
    :param new_layer_name: What the layer should be called
    :param symbology_layer: The symbology that we will import
    :param isRaster: Tells us if it's a raster or not
    :param description: The discription to give to the layer file
    :return: The path to the new layer
    """
    new_layer = new_layer_name + "_lyr"
    new_layer_save = os.path.join(output_folder, new_layer_name + ".lyr")

    if isRaster:
        arcpy.MakeRasterLayer_management(layer_base, new_layer)
    else:
        arcpy.MakeFeatureLayer_management(layer_base, new_layer)

    arcpy.ApplySymbologyFromLayer_management(new_layer, symbology_layer)
    arcpy.SaveToLayerFile_management(new_layer, new_layer_save)
    new_layer_instance = arcpy.mapping.Layer(new_layer_save)
    new_layer_instance.description = description
    new_layer_instance.save()
    return new_layer_save
Ejemplo n.º 16
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)
            symbologyLayr = arcpy.mapping.Layer(symbologyLayer)
            # rasLayer.symbology.
            arcpy.ApplySymbologyFromLayer_management(rasLayer, symbologyLayr)
            arcpy.mapping.AddLayer(df, rasLayer, "AUTO_ARRANGE")
            arcpy.AddMessage(
                str(time.ctime()) + ":" + symbologyLayer + "添加成功。。。")
            for legend in arcpy.mapping.ListLayoutElements(
                    mxd, "LEGEND_ELEMENT", "Legend"):
                print(legend.items)
            arcpy.RefreshActiveView()
            for legend in arcpy.mapping.ListLayoutElements(
                    mxd, "LEGEND_ELEMENT", "Legend"):
                print(legend.items)
            mxd.save()
    arcpy.mapping.ExportToJPEG(mxd, jpgpath, resolution=res)
Ejemplo n.º 17
0
def heatMapGen(radius, cellSize):
    print "Setting database and workspace..." + str(time.ctime())
    arcpy.env.workspace = "D:/GD/WGiSR/_Konferencje/Plener 2018/heatMap/data.gdb"
    print "         Database and workspace set! " + str(time.ctime())

    print "Setting local variables..." + str(time.ctime())
    mxd = arcpy.mapping.MapDocument(
        "D:/GD/WGiSR/_Konferencje/Plener 2018/heatMap/HeatMap.mxd")
    df = arcpy.mapping.ListDataFrames(mxd)[0]
    template = "D:/GD/WGiSR/_Konferencje/Plener 2018/heatMap/kd_temp_hypso.lyr"
    inData = "OSM_STOPS_2180"
    print "         Local variables set! " + str(time.ctime())

    print "     Generating Heat Map..." + str(time.ctime())
    arcpy.Delete_management("kd")
    arcpy.CheckOutExtension("Spatial")
    kd = arcpy.sa.KernelDensity(inData, "NONE", cellSize, radius,
                                "SQUARE_KILOMETERS")
    kd.save("kd")
    arcpy.BuildPyramids_management("kd")
    arcpy.MakeRasterLayer_management("kd")
    layer = arcpy.mapping.Layer("kd")
    tempLyr = arcpy.mapping.Layer(template)
    arcpy.ApplySymbologyFromLayer_management(layer, tempLyr)
    arcpy.mapping.AddLayer(df, layer)
    mxd.save()
    print "             Heat Map generated! " + str(time.ctime())

    print "     Exporting map..." + str(time.ctime())
    arcpy.mapping.ExportToJPEG(
        mxd,
        "D:/GD/WGiSR/_Konferencje/Plener 2018/heatMap/_genMaps/HeatMap_radius_"
        + str(radius) + ".jpg")
    print "             Map exported! " + str(time.ctime())
Ejemplo n.º 18
0
def add_raster(dataframe, raster, symbology_layer):

    layer_pointer = arcpy.mapping.Layer(raster)
    # set symbology from a pre-existing lyr file
    arcpy.ApplySymbologyFromLayer_management(layer_pointer, symbology_layer)
    # add to mxd
    arcpy.mapping.AddLayer(dataframe, layer_pointer, "BOTTOM")
Ejemplo n.º 19
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)
Ejemplo n.º 20
0
def add_feature(df, filename, symbology, TOCposition):
    # make a layer
    newlayer = arcpy.mapping.Layer(filename)
    print 'adding {0}'.format(filename)
    # apply the symbology
    arcpy.ApplySymbologyFromLayer_management(newlayer, os.path.join(os.getcwd(), symbology))
    # add new layer to current dataframe, at the top of the table of contents
    arcpy.mapping.AddLayer(df, newlayer, "TOP")
Ejemplo n.º 21
0
def zonal_hist(in_zone, in_value_raster, set_raster_symbology, region_c,
               use_name, temp_table, final_folder, snap):
    # In paths
    path_fc, in_species = os.path.split(in_zone)
    sp_group = in_species.split("_")[1]

    # out paths
    break_use = use_path.split("_")
    break_bool = False
    use_nm_folder = region_c  # starting point that will be used for use_nm_folder

    for v in break_use:
        if v != region_c:
            pass
        else:
            break_bool = True
        if break_bool:
            if v == region_c:
                continue
            else:
                use_nm_folder = use_nm_folder + "_" + v

    use_nm_folder = use_nm_folder.split(".")[0]
    print use_nm_folder

    if not os.path.exists(final_folder + os.sep + use_nm_folder):
        os.mkdir(final_folder + os.sep + use_nm_folder)

    out_tables = final_folder + os.sep + use_nm_folder
    run_id = in_species + "_" + use_nm_folder
    out_path_final = out_tables

    csv = run_id + '.csv'

    if os.path.exists(out_path_final + os.sep + csv):
        print("Already completed run for {0}".format(run_id))

    elif not os.path.exists(out_path_final + os.sep + csv):
        print(
            "Running Statistics...for species group {0} and raster {1}".format(
                sp_group, use_name))
        arcpy.CheckOutExtension("Spatial")

        arcpy.MakeRasterLayer_management(Raster(in_zone), "zone")
        arcpy.MakeRasterLayer_management(Raster(in_value_raster), "rd_lyr")
        arcpy.ApplySymbologyFromLayer_management("rd_lyr",
                                                 set_raster_symbology)
        temp_return, zone_time = zone("zone", "rd_lyr", temp_table, snap)

        list_fields = [f.name for f in arcpy.ListFields(temp_return)]
        att_array = arcpy.da.TableToNumPyArray((temp_return), list_fields)
        att_df = pd.DataFrame(data=att_array)
        att_df['LABEL'] = att_df['LABEL'].map(lambda x: x).astype(str)
        att_df.to_csv(out_path_final + os.sep + csv)
        print 'Final file can be found at {0}'.format(out_path_final + os.sep +
                                                      csv)
        print "Completed in {0}\n".format(
            (datetime.datetime.now() - zone_time))
def zonal_hist(in_zone, in_raster, set_raster_symbology, use_nm, temp_table,
               current_use):
    use_nm_folder = current_use
    if not os.path.exists(out_results + os.sep + use_nm_folder):
        os.mkdir(out_results + os.sep + use_nm_folder)
    symbology_loop = sy_path + os.sep + use_nm + '.lyr'
    out_tables = out_results + os.sep + use_nm_folder
    run_id = str(current_use) + "_" + str(use_nm)
    out_path_final = out_tables
    csv = run_id + '.csv'
    dbf = csv.replace('csv', 'dbf')

    if os.path.exists(out_path_final + os.sep + csv):
        print("Already completed run for {0}".format(run_id))

    elif not os.path.exists(out_path_final + os.sep + dbf):
        print("Running Statistics...for {0} v raster {1}".format(
            current_use, use_nm))
        arcpy.CheckOutExtension("Spatial")
        arcpy.MakeRasterLayer_management(Raster(in_zone), "zone")
        arcpy.ApplySymbologyFromLayer_management("zone", set_raster_symbology)
        arcpy.MakeRasterLayer_management(Raster(in_raster), "rd_lyr")
        arcpy.ApplySymbologyFromLayer_management("rd_lyr", symbology_loop)
        temp_return, start_loop = zone("zone", "rd_lyr", temp_table)

        list_fields = [f.name for f in arcpy.ListFields(temp_return)]
        att_array = arcpy.da.TableToNumPyArray(temp_return, list_fields)
        att_df = pd.DataFrame(data=att_array)
        att_df.to_csv(out_path_final + os.sep + csv)
        # arcpy.TableToTable_conversion(temp_return, out_path_final, dbf)

        print 'Final file can be found at {0}'.format(out_path_final + os.sep +
                                                      csv)
        print "Completed in {0}\n".format(
            (datetime.datetime.now() - start_time))

    elif not os.path.exists(out_path_final + os.sep + csv):
        list_fields = [
            f.name for f in arcpy.ListFields(out_path_final + os.sep + dbf)
        ]
        att_array = arcpy.da.TableToNumPyArray((out_path_final + os.sep + dbf),
                                               list_fields)
        att_df = pd.DataFrame(data=att_array)
        att_df['LABEL'] = att_df['LABEL'].map(lambda x: x).astype(str)
        att_df.to_csv(out_path_final + os.sep + csv)
Ejemplo n.º 23
0
 def ApplyStyle(self, target_layer_name, style_layer_path):
     print('\nStyling layer %s.  Using layer as reference:  %s' %
           (target_layer_name, style_layer_path))
     dataframe = self._getDataFrame()
     mxd = self.getMXDFile()
     target_layer = arcpy.mapping.ListLayers(mxd, target_layer_name,
                                             dataframe)[0]
     arcpy.ApplySymbologyFromLayer_management(target_layer,
                                              style_layer_path)
Ejemplo n.º 24
0
def add_raster(dataframe, raster, layername, path, symbology_layer):
    # add raster to a mxd file
    print 'adding {0}'.format(raster)
    # create pointer to raster layer objects
    # input to layer pointer needs to be path to raster, not raster object
    layer_pointer = arcpy.mapping.Layer(raster)
    # set symbology from a pre-existing lyr file
    arcpy.ApplySymbologyFromLayer_management(layer_pointer, symbology_layer)
    # add to mxd
    arcpy.mapping.AddLayer(dataframe, layer_pointer, "BOTTOM")
Ejemplo n.º 25
0
def AddToMap(feature_or_raster, layer_file=None, zoom_to=False):
    """
    Adds provided to the map document after removing any layers of the same
    name.
    :param feature_or_raster: feature class or raster dataset
    :param layer_file: layer file
    :param zoom_to: True to zoom to the added object
    :return: None
    """
    # Add layer to map
    arcpy.AddMessage("Adding layer to map document")
    if arcpy.ListInstallations()[0] == 'arcgispro':
        p = arcpy.mp.ArcGISProject("CURRENT")
        m = p.activeMap
        layer_path = arcpy.Describe(
            feature_or_raster
        ).catalogPath  #arcpy.Describe calls metadata, so this gives full path
        for existingLayer in m.listLayers(m):
            if existingLayer.name == feature_or_raster:
                m.remove_layer(existingLayer)
        m.addDataFromPath(layer_path)
        # TODO: revisit layer file application in Pro.
        if layer_file:
            arcpy.ApplySymbologyFromLayer_management(feature_or_raster,
                                                     layer_file)
        #if zoom_to:
        #   m.extent = layer.getSelectedExtent()
        del p, m

    else:
        mxd = arcpy.mapping.MapDocument("CURRENT")
        df = mxd.activeDataFrame
        layer_path = arcpy.Describe(feature_or_raster).catalogPath
        layer = arcpy.mapping.Layer(layer_path)
        for existingLayer in arcpy.mapping.ListLayers(mxd, "", df):
            if existingLayer.name == layer.name:
                arcpy.mapping.RemoveLayer(df, existingLayer)
        arcpy.mapping.AddLayer(df, layer)
        if layer_file:
            arcpy.ApplySymbologyFromLayer_management(layer.name, layer_file)
        if zoom_to:
            df.extent = layer.getSelectedExtent()
        del mxd, df, layer
Ejemplo n.º 26
0
def export_to_jpeg(plot_type, plot_file_name, symbologyLayer):
    # modify symbology if necessary
    mxd = arcpy.mapping.MapDocument(plot_mxd_file)
    df = arcpy.mapping.ListDataFrames(mxd)[0]
    lyr = arcpy.mapping.ListLayers(mxd, plot_type, df)[0]
    arcpy.ApplySymbologyFromLayer_management(lyr, symbologyLayer)
    lyr.visible = True
    lyr.transparency = 0
    arcpy.mapping.ExportToJPEG(mxd, plot_file_name + ".jpg", "PAGE_LAYOUT", resolution=800)
    del mxd
Ejemplo n.º 27
0
def add_map_layer(file_name, symbol_layer, name='layer', data_frame=None):
    """creates and adds a symbolized layer to a data frame"""
    if not data_frame:
        data_frame = arcpy.mapping.ListDataFrames(
            arcpy.mapping.MapDocument("CURRENT"))[0]
    layer = arcpy.mapping.Layer(file_name)
    layer.name = name
    arcpy.ApplySymbologyFromLayer_management(layer, symbol_layer)
    arcpy.mapping.AddLayer(data_frame, layer)
    return layer
Ejemplo n.º 28
0
def zonal_hist(in_zone_data, in_value_raster, set_raster_symbol, use_name,
               results_folder, huc12, temp_table, region_c, snap):

    # out paths
    break_use = os.path.basename(use_path).split("_")
    break_bool = False
    use_nm_folder = region_c  # starting point that will be used for use_nm_folder

    for v in break_use:  # SEE TODO
        if v != region and v != 'CDL':
            # 'Area' and v != 'AK' and v != '2S'and v != '55N' and v != 'Area' and v != '4N' and v != '20N':
            pass
        else:
            break_bool = True
        if break_bool:
            if v == region_c:
                pass
            else:
                use_nm_folder = use_nm_folder + "_" + v

    use_nm_folder = use_nm_folder.split(".")[0]

    out_folder = results_folder + os.sep + use_nm_folder
    if not os.path.exists(out_folder):
        os.mkdir(out_folder)

    # parse out information needed for file names
    # huc_12_value = huc12.replace('NHDPlus', '_')
    huc_12_value = huc12
    run_id = use_nm_folder + "_" + huc_12_value
    csv = out_folder + os.sep + run_id + '.csv'
    print csv
    if os.path.exists(csv):
        print("Already completed run for {0}".format(run_id))
    elif not os.path.exists(csv):
        print("Running Statistics...for HUC2 {0} and raster {1}".format(
            huc_12_value, use_name))
        arcpy.CheckOutExtension("Spatial")
        arcpy.Delete_management("rd_lyr")
        arcpy.Delete_management("HUC12_lyr")
        arcpy.MakeFeatureLayer_management(in_zone_data, "HUC12_lyr")
        arcpy.MakeRasterLayer_management(Raster(in_value_raster), "rd_lyr")
        arcpy.ApplySymbologyFromLayer_management("rd_lyr", set_raster_symbol)
        temp_return, zone_time = zone("HUC12_lyr", "rd_lyr", temp_table, snap)

        list_fields = [f.name for f in arcpy.ListFields(temp_return)]
        att_array = arcpy.da.TableToNumPyArray(temp_return, list_fields)
        att_df = pd.DataFrame(data=att_array)
        att_df['LABEL'] = att_df['LABEL'].map(lambda x: x).astype(str)
        att_df.to_csv(csv)
        print 'Final file can be found at {0}'.format(csv)
        # arcpy.TableToTable_conversion(temp_return, outpath_final, dbf)
        arcpy.Delete_management("in_memory\\temp_table")

        print "Completed in {0}".format((datetime.datetime.now() - zone_time))
Ejemplo n.º 29
0
    def create_new_prjx(self, a_field, a_group):
        aprx = arcpy.mp.ArcGISProject(self._config.baseprjx)
        tempprjx = TempFileName.generate_temporary_file_name(suffix=".aprx")
        temp_filegeodb = FileGeodatabaseHelper().new_file_geodatabase()
        self.log(tempprjx)
        self.log(temp_filegeodb)
        aprx.saveACopy(tempprjx)
        del aprx
        self.log(f"deleted handle on {self._config.baseprjx}")
        working_aprx = arcpy.mp.ArcGISProject(tempprjx)
        self.log(f"Got {working_aprx}")
        m = working_aprx.listMaps(self._config.mapname)[0]
        lyr_file = arcpy.mp.LayerFile(self._config.layerfile)
        self.log(f"Got {lyr_file}")
        select_lyr = lyr_file.listLayers("*")[0]
        temp_lyr = "temp_lyr"
        self.log(f"making a temp feature layer with {a_field} = '{a_group}'")
        arcpy.MakeFeatureLayer_management(select_lyr, temp_lyr, f"{a_field} = '{a_group}'")
        # with arcpy.da.SearchCursor(temp_lyr, ['*']) as cursor:
        #     for row in cursor:
        #         print(row)

        # we know need to do a spatial join between the security polygon and all the other layers
        # we have to reverse the order of layers processed for the addDataFromPath
        layer_list = [l.name for l in m.listLayers("*")]
        for layer_name in reversed(layer_list):
            a_layer = m.listLayers(layer_name)[0]
            self.log(f"Processing {a_layer.name}")
            if a_layer.isBasemapLayer or not a_layer.isFeatureLayer:
                continue

            result = arcpy.GetCount_management(a_layer)
            self.log(f"before selection {a_layer.name} count:{result}")
            arcpy.SelectLayerByLocation_management(a_layer, 'INTERSECT', temp_lyr, 30)
            result = arcpy.GetCount_management(a_layer)
            self.log(f"after selection {a_layer.name} count:{result}")
            name = a_layer.dataSource.split('\\')[-1].split('.')[-1]
            self.log(f"New layer name:{name}")
            arcpy.FeatureClassToFeatureClass_conversion(a_layer, temp_filegeodb, name)
            new_layer = m.addDataFromPath(f"{temp_filegeodb}\\{name}")
            temp_lyrx_file = TempFileName().generate_temporary_file_name(suffix=".lyrx")
            self.log(f"Temp lyrx file: {temp_lyrx_file}")
            a_layer.saveACopy(temp_lyrx_file)
            arcpy.ApplySymbologyFromLayer_management(new_layer, temp_lyrx_file)
            # reset all the usual stuff
            new_layer.visible = a_layer.visible
            new_layer.maxThreshold = a_layer.maxThreshold
            new_layer.minThreshold = a_layer.minThreshold
            new_layer.showLabels = a_layer.showLabels
            new_layer.transparency = a_layer.transparency
            m.removeLayer(a_layer)
            working_aprx.save()
        fp = working_aprx.filePath
        del working_aprx
        return fp
Ejemplo n.º 30
0
def add_feature(df, filename, symbology, TOCposition):
    # make a layer
    newlayer = arcpy.mapping.Layer(filename)
    print 'adding {0}'.format(filename)
    if symbology:
        # apply the symbology
        arcpy.ApplySymbologyFromLayer_management(newlayer, symbology)
    else:
        print "No symbology specified for {0}!".format(filename)
    # add new layer to current dataframe, at the top of the table of contents
    arcpy.mapping.AddLayer(df, newlayer, "TOP")