Ejemplo n.º 1
0
def networkPreProcessing(bikeNetwork, footNetwork):
    arcpy.Delete_management(
        "C:/Users/Simon/Documents/GitHub/Enrichment/networkPr_update.shp", "")
    bikeNetworkFL = arcpy.CopyFeatures_management(
        bikeNetwork,
        "C:/Users/Simon/Documents/GitHub/Enrichment/bikeNetworkUpdate")
    arcpy.MakeFeatureLayer_management(bikeNetworkFL, "bikeNetworkPr_update")
    expressionBike = """("navigatie" = 'onderdeel van rotonde' OR "navigatie" = 'onderdeel van kruispunt' OR "wegtype" = 'bromfietspad (langs weg)' OR "wegtype" = 'fietspad (langs weg)' OR "wegtype" = 'fietsstraat' OR "wegtype" = 'solitair bromfietspad' OR "wegtype" = 'solitair fietspad' OR "wegtype" = 'voetgangersdoorsteekje' OR "wegtype" = 'voetgangersgebied' OR "wegtype" = 'weg met fiets(suggestie)strook' ) AND "verlichtin" = ' ' OR "verlichtin" = 'beperkt verlicht (bijvoorbeeld alleen bij kruispunten)' OR "verlichtin" = 'goed verlicht' OR "verlichtin" = 'niet verlicht' OR "verlichtin" = 'ONBEKEND'"""
    arcpy.SelectLayerByAttribute_management("bikeNetworkPr_update",
                                            "NEW_SELECTION", expressionBike)
    if int(arcpy.GetCount_management("bikeNetworkPr_update").getOutput(0)) < 0:
        arcpy.DeleteRows_management("bikeNetworkPr_update")

    footNetworkFL = arcpy.CopyFeatures_management(
        footNetwork,
        "C:/Users/Simon/Documents/GitHub/Enrichment/footNetworkUpdate")
    arcpy.MakeFeatureLayer_management(footNetworkFL, "footNetworkPr_update")
    expressionFoot = """VERHARDINGSBREEDTEKLASSE = '< 2 meter' OR VERHARDINGSBREEDTEKLASSE = '2 - 4 meter' AND (TYPEWEG_1 = 'overig' AND (HOOFDVERKEERSGEBRUIK_1 = 'gemengd verkeer' OR HOOFDVERKEERSGEBRUIK_1 = 'voetgangers') AND (VERHARDINGSTYPE = 'half verhard' OR VERHARDINGSTYPE = 'onbekend' OR VERHARDINGSTYPE = 'onverhard'))"""
    arcpy.SelectLayerByAttribute_management("footNetworkPr_update",
                                            "NEW_SELECTION", expressionFoot)
    if int(arcpy.GetCount_management("footNetworkPr_update").getOutput(0)) < 0:
        arcpy.DeleteRows_management("footNetworkPr_update")

    updatedNetworkBike = arcpy.FeatureClassToShapefile_conversion(
        "bikeNetworkPr_update", "C:/Users/Simon/Documents/GitHub/Enrichment/")
    updatedNetworkFoot = arcpy.FeatureClassToShapefile_conversion(
        "footNetworkPr_update", "C:/Users/Simon/Documents/GitHub/Enrichment/")
    arcpy.Delete_management(
        "C:/Users/Simon/Documents/GitHub/Enrichment/networkUpdate.shp",
        "C:/Users/Simon/Documents/GitHub/Enrichment/footNetworkUpdate.shp")
    return updatedNetwork
Ejemplo n.º 2
0
def MyParallelFunction(NameOut, TrackIn, SegmentsIn):
    arcpy.FeatureClassToShapefile_conversion(TrackIn, "D:\GIMA\TemporaryShp")
    arcpy.FeatureClassToShapefile_conversion(SegmentsIn,
                                             "D:\GIMA\TemporaryShp")

    InTrack = os.path.join("D:\GIMA\TemporaryShp", NameOut + ".shp")
    InSegment = os.path.join("D:\GIMA\TemporaryShp",
                             "Road_" + NameOut + ".shp")
    print "running mapmatcher for file: " + str(NameOut)
    opt = mapMatch(InTrack, InSegment, 300, 25, 100)
    print "writing mapmatcher" + str(NameOut) + "To disk"
    exportPath(opt, str(NameOut) + ".shp")
Ejemplo n.º 3
0
    def execute(self, parameters, messages):
        """The source code of the tool."""

        arcpy.env.overwriteOutput = True

        Drainage_Lines = parameters[0].valueAsText
        ecmwf_watershed_name = parameters[1].valueAsText
        ecmwf_subbasin_name = parameters[2].valueAsText
        wrf_hydro_watershed_name = parameters[3].valueAsText
        wrf_hydro_aubbasin_name = parameters[4].valueAsText
        Catchment_Features = parameters[5].valueAsText
        SPT_out_folder = parameters[6].valueAsText

        script_directory = os.path.dirname(__file__)
        arcpy.ImportToolbox(
            os.path.join(os.path.dirname(script_directory), "RAPID Tools.pyt"))

        #Add watershed names to drainagelines
        arcpy.AddSPTFields_RAPIDTools(Drainage_Lines, ecmwf_watershed_name,
                                      ecmwf_subbasin_name,
                                      wrf_hydro_watershed_name,
                                      wrf_hydro_aubbasin_name)

        #Dissolve Catchments
        Dissolved_Catchments = os.path.join(
            os.path.dirname(Catchment_Features), "WatershedBoundary")
        #Input_Catchment_Features to Dissolved_Catchments
        arcpy.Dissolve_management(Catchment_Features, Dissolved_Catchments)

        #export shapefiles to new folder
        inputs = [Dissolved_Catchments, Drainage_Lines]
        arcpy.FeatureClassToShapefile_conversion(inputs, SPT_out_folder)

        return
Ejemplo n.º 4
0
 def csv2points(self,
                spatial_ref=26942,
                x_field_name='X',
                y_field_name='Y'):
     """
     Converts csv file to point shapefile
     :param spatial_ref: INT of factory code of a SpatialReference. DEFAULT = 26942 (NAD83 California II)
                             > must be a PROJECTED COORDINATE SYSTEM
                             > check docs/projected_coordinate_systems.pdf for more
     :param x_field_name: STR
     :param y_field_name: STR
     :param z_field_name: STR
     :return: None
     """
     print(" * setting spatial reference ...")
     self.sr = arcpy.SpatialReference(spatial_ref)
     arcpy.env.outputCoordinateSystem = self.sr
     print(" * reading %s and creating XYEvent layer ..." % self.csv_file)
     arcpy.MakeXYEventLayer_management(table=self.csv_file,
                                       in_x_field=x_field_name,
                                       in_y_field=y_field_name,
                                       out_layer=self.csv_name + "_pts",
                                       spatial_reference=self.sr)
     print(" * converting XYEvent layer to %s ..." % self.point_shp)
     arcpy.FeatureClassToShapefile_conversion(self.csv_name + "_pts",
                                              self.out_dir)
     print("   - OK")
Ejemplo n.º 5
0
def main():
    startTime = dt.datetime.now()
    print("Script run at {0}.".format(startTime))
    
    p = Path(__file__).parents[0]
    
    # `Scenario_1024` should be changed to the appropriate scenario number 
    # output by Emme.
    links_shapefile = os.path.join(str(p), 'New_Project', 'Media', 
                                           'Scenario_1024', 'emme_links.shp') 
    in_field = 'ID'
    join_table = os.path.join(str(p), 'volumes.csv')
    join_field = 'UNIQUEID'


    arcpy.TableToTable_conversion(join_table, str(p), 'volumes_converted.dbf' )
    converted_table = os.path.join(str(p), 'volumes_converted.dbf')

    
    joined_file = arcpy.JoinField_management(
                                            links_shapefile,
                                            in_field,
                                            converted_table,
                                            join_field)

    arcpy.FeatureClassToShapefile_conversion(joined_file, os.path.join(str(p)))
    
    endTime = dt.datetime.now()
    print("Script finished in {0}.".format(endTime - startTime))
Ejemplo n.º 6
0
def shp2wkt(fc, outcsv, fieldin_list):
    #make a copy in a temporary folder removing any Z, M values
    temp_path = os.path.join(
        os.path.dirname(fc),
        'temp' + dt.datetime.today().strftime('%y%b%d_%H%M%S'))
    os.mkdir(temp_path)
    arcpy.env.outputZFlag = 'Disabled'
    arcpy.env.outputMFlag = 'Disabled'
    arcpy.FeatureClassToShapefile_conversion(fc, temp_path)
    #convert to WKT and print
    #source fc should be WGS84 for BQ
    fc_temp = os.path.join(temp_path, os.path.basename(fc))
    cursor = arcpy.da.SearchCursor(fc_temp, fieldin_list)
    with open(outcsv, 'w') as f:
        f_writer = csv.writer(f,
                              delimiter=',',
                              quotechar='"',
                              lineterminator='\n')
        for row in cursor:
            f_writer.writerow([
                s.encode('utf8') if isinstance(s, unicode) else s for s in row
            ])
    #delete the temporary shapefile and directory
    arcpy.Delete_management(fc_temp)
    os.rmdir(temp_path)
    return outcsv
Ejemplo n.º 7
0
    def execute(self, parameters, messages):
    
        arcpy.env.overwriteOutput = True
        #contourLines = parameters[0].valueAsText
        parcelPolygon = r'C:\Users\crpge\Desktop\Medina\ParcelLines\parcelp.shp' #parameters[1].valueAsText
        parcelId = parameters[2].valueAsText  
        
        #parcelShape = arcpy.Describe(parcelPolygon).shapeFieldName

        mxd = arcpy.mapping.MapDocument(r"C:\Users\crpge\Desktop\Medina\Medina.mxd")
        df = arcpy.mapping.ListDataFrames(mxd)
        
        #input = parcelPolygon
        #in_path = arcpy.Describe(input).catalogPath

        out_path = r'C:\Users\crpge\Desktop\Medina\CreatedData' 
        try: 
            whereClause = '"PPNUMBER"' + " = '" + str(parcelId) + "'"
            arcpy.MakeFeatureLayer_management(parcelPolygon, "parcelOutput", whereClause)
        except Exception:
            arcpy.AddError("There was an issue finding the parcel number")
            raise arcpy.ExecuteError

        #arcpy.SelectLayerByAttribute_management ('parcelOutput', 'NEW_SELECTION', '"PPNUMBER" = "03608A08027"')
        #arcpy.SelectLayerByAttribute_management ('lyr', 'NEW_SELECTION', '"PPNUMBER" =  {}'.format(parcelId))
        #arcpy.CopyFeatures_management("parcelOutput", outLayer)
        #addLayer = arcpy.mapping.Layer("parcelOutput")


        #initially
        arcpy.FeatureClassToShapefile_conversion('parcelOutput', out_path)
Ejemplo n.º 8
0
def GNIS_Download(save_dir,datasets):
    arcpy.env.overwriteOutput = True
    # List of shapefiles used for the merge
    shape_files = []
    dirpath = save_dir
    fileList = os.listdir(dirpath)
    for FileName in fileList:
        os.remove(dirpath + '\\' + FileName)
    url = "https://viewer.nationalmap.gov/tnmaccess/api/products?"
    parameters = {"datasets": datasets}

    response = requests.get(url, params=parameters)

    data = response.json()
    down_len = len(data['items'])
    print ('%d items returned from TNM API'%down_len)
    print ('Data will be save to:', save_dir)
    for i in range(0,down_len-1):
        url_save = data['items'][i]['downloadURL']
        title = url_save.split('/')
        title = title[-1]
        title = title.replace(" ", "_")
        if (title != 'AllStates.zip' and title != 'NationalFile.zip' and title != 'FM_Features.zip' and title != 'GU_Features.zip'):
            print ('Downloading data from:', url_save)
            urllib.request.urlretrieve(url_save, save_dir + '\\' + title)
            # Unzip the data
            arcpy.AddMessage("Unzipping File...")
            zip_ref = zipfile.ZipFile(save_dir + '\\' + title)
            zip_ref.extractall(save_dir)
            zip_ref.close()
            os.remove(save_dir +'\\'+title)

            arcpy.AddMessage("Converting text files to csv...")
            # Convert .txt files into .csv
            for txt_file in glob.glob(os.path.join(save_dir, '*.txt')):
                with open(txt_file, "r", encoding='UTF-8') as input_file:
                    in_txt = csv.reader(input_file, delimiter='|')
                    filename = os.path.splitext(os.path.basename(txt_file))[0] + '.csv'

                    with open(os.path.join(save_dir, filename), 'w', encoding='UTF-8') as output_file:
                        out_csv = csv.writer(output_file)
                        out_csv.writerows(in_txt)
                os.remove(txt_file)

            arcpy.AddMessage("Converting csv to shapefiles...")
            # Convert csv to shapefile
            # All the shapefiles should save to the individual state folder
            for csv_file in glob.glob(os.path.join(save_dir, '*.csv')):
                print(csv_file)
                temp_name = os.path.splitext(os.path.basename(csv_file))[0]
                arcpy.MakeXYEventLayer_management(csv_file, 'PRIM_LONG_DEC', 'PRIM_LAT_DEC', temp_name)
                arcpy.FeatureClassToShapefile_conversion(temp_name, save_dir)
                os.remove(csv_file)
                print ('Selecting Only summit points...')
                arcpy.Select_analysis(save_dir+'\\'+temp_name+'.shp',save_dir+'\\'+temp_name+'Summit.shp','"FEATURE_CL" = \'Summit\'')
                shape_files.append(save_dir+'\\'+temp_name + 'Summit.shp')
            print ('')
    print ('Merging files...')
    arcpy.Merge_management(shape_files, save_dir+'\\GNIS_AllSummitPoint.shp')
    return(save_dir+'\\GNIS_AllSummitPoint.shp')
Ejemplo n.º 9
0
def Fotopunkte():
    """create Fotopunkte.txt and shp from all fotologs, the lost frames and the small latency caused frame number not
    match can't be detected """
    global project_dir, t
    shp_dir = dir_generate(project_dir + '/shp')
    fotolog = project_dir + '/foto_log'
    foto_shp = open(project_dir + '/shp/Fotopunkte.txt', 'w')
    foto_shp.write('weg_num,foto_id,Color,Depth,Lon,Lat,jpg_path,Uhrzeit\n')
    for x in os.listdir(fotolog):
        file_name = '{}/{}'.format(fotolog, x)
        with open(file_name, 'r') as log:
            for data in log:
                data = data.split(',')
                foto_id, Color, Depth, Long, Lat, time = data[0], data[
                    1], data[2], data[4], data[3], data[8]
                weg_nummer = x[:-4]
                path = '{}/jpg/{}-{}.jpg'.format(project_dir, weg_nummer,
                                                 Color)
                shp_line = '{},{},{},{},{},{},{},{}'.format(
                    weg_nummer, foto_id, Color, Depth, Long, Lat, path, time)
                foto_shp.write(shp_line)
        t.insert(END, 'processed {}\n'.format(x))
    foto_shp.close()
    arcpy.env.overwriteOutput = True
    spRef = 'WGS 1984'
    management.MakeXYEventLayer(shp_dir + '/Fotopunkte.txt', 'Lat', 'Lon',
                                'Fotopunkte', spRef)
    arcpy.FeatureClassToShapefile_conversion('Fotopunkte', shp_dir)
    t.insert(END, 'Fotopunkte.shp fertig\n')
Ejemplo n.º 10
0
def export_fcs_from_main_gdb(the_scenario, logger):
    # export fcs from the main.GDB to individual shapefiles
    logger.info("start: export_fcs_from_main_gdb")
    start_time = datetime.datetime.now()

    # export network and locations fc's to shapefiles
    main_gdb = the_scenario.main_gdb
    output_path = the_scenario.lyr_files_dir
    input_features = "\""

    logger.debug("delete the temp_networkx_shp_files dir")
    if os.path.exists(output_path):
        logger.debug("deleting temp_networkx_shp_files directory.")
        rmtree(output_path)

    if not os.path.exists(output_path):
        os.makedirs(output_path)
        logger.debug("finished: create_temp_gdbs_dir")

    # get the locations and network feature layers
    for fc in ['\\locations;', '\\network\\intermodal;', '\\network\\locks;', '\\network\\pipeline_prod_trf_rts;',
               '\\network\\pipeline_crude_trf_rts;', '\\network\\water;', '\\network\\rail;', '\\network\\road']:
        input_features += main_gdb + fc
    input_features += "\""
    arcpy.FeatureClassToShapefile_conversion(Input_Features=input_features, Output_Folder=output_path)

    logger.debug("finished: export_fcs_from_main_gdb: Runtime (HMS): \t{}".format(
        ftot_supporting.get_total_runtime_string(start_time)))
def sbdd_ExportToShape (myFC):
    if arcpy.Exists(theOF + myFC + "/" + myFC + ".shp"):
        arcpy.Delete_management(theOF + myFC + "/" + myFC + ".shp")
    if arcpy.Exists(theOF + myFC + "/" + theST + "_" + myFC + ".shp"):
        arcpy.Delete_management(theOF + myFC + "/" + theST + "_" +
                                myFC + ".shp")
    if arcpy.Exists(myFC):  #then export it
        arcpy.AddMessage("          Exporting " + myFC)
        if myFC == "Wireless":
            arcpy.DeleteField_management(myFC, "STATEABBR")
            #arcpy.DeleteField_management(myFC, "SBDD_ID")
        if myFC == "Address":
            #dropFields = ["ADDRESS","BLDGNBR","PREDIR","STREETNAME","STREETTYPE","SUFEDIR","CITY","STATECODE","ZIP5","ZIP4","LATITUDE","LONGITUDE","SBDD_ID"]
            dropFields = ["ADDRESS","BLDGNBR","PREDIR","STREETNAME","STREETTYPE","SUFEDIR","CITY","STATECODE","ZIP5","ZIP4","LATITUDE","LONGITUDE"]
            arcpy.DeleteField_management(myFC,dropFields)
        #arcpy.AddMessage("myFC = " + myFC)
        #arcpy.AddMessage("theOF = " + theOF)
        

        arcpy.FeatureClassToShapefile_conversion(myFC, theOF + myFC)

        #arcpy.AddMessage(theOF + myFC + "/" + myFC + ".shp")
        #arcpy.AddMessage(theOF + myFC + "/" + theST + "_" + myFC + ".shp")
        arcpy.Rename_management(theOF + myFC + "/" + myFC + ".shp", theOF +
                                myFC + "/" + theST + "_" + myFC + ".shp")
    del myFC
    return ()
Ejemplo n.º 12
0
 def Convert(output, aglist):
     if not os.path.exists(output): os.makedirs(output)
     arcpy.FeatureClassToShapefile_conversion(aglist, output)
     shp_ease = os.path.join(output, "AgEasements.shp")
     shp_asa = os.path.join(output, "Agsecurity.shp")
     shp_apps = os.path.join(output, "AgApplications.shp")
     arcpy.DeleteField_management(shp_asa, deleteFields)
     arcpy.DeleteField_management(shp_ease, deleteFields)
Ejemplo n.º 13
0
def Renamefield_Pro(temp_shape, temp_out, workspace, ShapeFileName):

    RenameFields = [
        "ORIGINTABLE", "ORIGINCHECK", "REVIEWSTATUS", "CORRECTIONSTATUS",
        "VERIFICATIONSTATUS", "REVIEWTECHNICIAN", "REVIEWDATE",
        "CORRECTIONTECHNICIAN", "CORRECTIONDATE", "VERIFICATIONTECHNICIAN",
        "VERIFICATIONDATE", "LIFECYCLESTATUS", "LIFECYCLEPHASE"
    ]
    NewNames = [
        "ORIG_TABLE", "ORIG_CHECK", "ERROR_DESC", "COR_STATUS", "VER_STATUS",
        "REV_TECH", "REV_DATE", "COR_TECH", "COR_DATE", "VER_TECH", "VER_DATE",
        "STATUS", "PHASE"
    ]

    arcpy.CopyFeatures_management(temp_shape, temp_out)

    fields = arcpy.ListFields(
        temp_out)  #get a list of fields for each feature class

    for field in fields:
        if "REVTABLEMAIN" in field.name:
            if field.type == "OID" or field.type == "Geometry":
                continue
            if "OBJECTID" in field.name:
                ## Manage OID field
                arcpy.AddField_management(temp_out, "FeatureOID", field.type)
                expr = "!" + field.name + "!"
                arcpy.CalculateField_management(temp_out, "FeatureOID", expr,
                                                "PYTHON3")
                arcpy.DeleteField_management(temp_out, field.name)
                continue

            fieldNames = field.name.split("_")
            outname = fieldNames[1]
            if fieldNames[1] in RenameFields:
                i = RenameFields.index(outname)
                outname = NewNames[i]
            # add a new field using the same properties as the original field
            arcpy.AddField_management(temp_out, outname, field.type)

            # calculate the values of the new field
            # set it to be equal to the old field
            exp = "!" + field.name + "!"
            arcpy.CalculateField_management(temp_out, outname, exp, "PYTHON3")

            # delete the old fields
            arcpy.DeleteField_management(temp_out, field.name)
        else:
            if field.type == "OID" or field.type == "Geometry":
                continue
            arcpy.DeleteField_management(temp_out, field.name)

    ##Save the layer as a shapefile
    arcpy.FeatureClassToShapefile_conversion(temp_out, workspace)
    shape_1 = workspace + "\\tmp_out.shp"
    arcpy.Rename_management(shape_1, ShapeFileName)
Ejemplo n.º 14
0
def matchershp():
    """create the shp from the matcher.txt"""
    global project_dir, t
    shp_dir = dir_generate(project_dir + '/shp')
    arcpy.env.overwriteOutput = True
    spRef = 'WGS 1984'
    management.MakeXYEventLayer(shp_dir + '/matcher.txt', 'Lon', 'Lat',
                                'Fotopunkte', spRef)
    arcpy.FeatureClassToShapefile_conversion('Fotopunkte', shp_dir)
    t.insert(END, 'Fotopunkte.shp fertig\n')
Ejemplo n.º 15
0
def networkPreProcessing(objects):
    arcpy.Delete_management("C:/Users/Simon/Documents/GitHub/Enrichment/networkPr_update.shp")
    networkFL = arcpy.CopyFeatures_management(objects, "C:/Users/Simon/Documents/GitHub/Enrichment/networkUpdate")
    arcpy.MakeFeatureLayer_management(networkFL, "networkPr_update")
    expression = """("navigatie" = 'onderdeel van rotonde' OR "navigatie" = 'onderdeel van kruispunt' OR "wegtype" = 'bromfietspad (langs weg)' OR "wegtype" = 'fietspad (langs weg)' OR "wegtype" = 'fietsstraat' OR "wegtype" = 'solitair bromfietspad' OR "wegtype" = 'solitair fietspad' OR "wegtype" = 'voetgangersdoorsteekje' OR "wegtype" = 'voetgangersgebied' OR "wegtype" = 'weg met fiets(suggestie)strook' ) AND "verlichtin" = ' ' OR "verlichtin" = 'beperkt verlicht (bijvoorbeeld alleen bij kruispunten)' OR "verlichtin" = 'goed verlicht' OR "verlichtin" = 'niet verlicht' OR "verlichtin" = 'ONBEKEND'"""
    arcpy.SelectLayerByAttribute_management("networkPr_update", "NEW_SELECTION", expression)
    if int(arcpy.GetCount_management("networkPr_update").getOutput(0)) < 0:
        arcpy.DeleteRows_management("networkPr_update")
    updatedNetwork = arcpy.FeatureClassToShapefile_conversion("networkPr_update", "C:/Users/Simon/Documents/GitHub/Enrichment/")
    return updatedNetwork
Ejemplo n.º 16
0
def featurecls_to_featurecls(inShp, outShp):
    """
    Record feature layer in a file
    Useful when we are using Network Analyst
    """

    import os

    arcpy.FeatureClassToShapefile_conversion(Input_Features=inShp,
                                             Output_Folder=outShp)
Ejemplo n.º 17
0
def DrawRadialFlows():

    # Try to assign the spatial reference by using the Well-Known ID for the input
    try:
        spRef = arcpy.SpatialReference(int(wkid))
    except:
        # If the SR cannot be created, assume 4326
        arcpy.AddWarning(
            "Problem creating the spatial reference!! Assumed to be WGS84 (wkid: 4326)"
        )
        spRef = arcpy.SpatialReference(4326)

    # Local variable:
    out_flows_fc = r"in_memory\FlowsLineXY"
    out_tbl = r"in_memory\tmpTable"
    out_Name = "Telecoupling Flows"

    if inTable and inTable != "#":

        try:
            # XY To Line
            arcpy.AddMessage('Creating Radial Flow Lines from Input File ...')
            arcpy.SetProgressorLabel(
                'Creating Radial Flow Lines from Input File ...')
            if id_field and flow_amnt:
                arcpy.XYToLine_management(in_table=inTable,
                                          out_featureclass=out_flows_fc,
                                          startx_field=startX_field,
                                          starty_field=startY_field,
                                          endx_field=endX_field,
                                          endy_field=endY_field,
                                          line_type=lineType_str,
                                          id_field=id_field,
                                          spatial_reference=spRef)

                arcpy.CopyRows_management(inTable, out_tbl)
                ## JOIN output flows with attribute from input table
                arcpy.JoinField_management(out_flows_fc, id_field, out_tbl,
                                           id_field, flow_amnt)

            # Process: Create a feature layer from the joined feature class to send back as output to GP tools
            out_fl = arcpy.MakeFeatureLayer_management(out_flows_fc, out_Name)

            # Send string of (derived) output parameters back to the tool
            arcpy.SetParameter(9, out_fl)

            # Execute FeatureClassToGeodatabase
            arcpy.AddMessage("Converting Feature Class to Shapefile...")
            arcpy.FeatureClassToShapefile_conversion(out_flows_fc,
                                                     arcpy.env.scratchFolder)

        except Exception:
            e = sys.exc_info()[1]
            arcpy.AddError('An error occurred: {}'.format(e.args[0]))
Ejemplo n.º 18
0
def export_SHP_from_GDB(input_path):
    for root, dirs, files in os.walk(importPath):
        for d in dirs:
            if d.endswith('.gdb'):
                print 'Working on -', d
                env.workspace = os.path.join(root, d)
                fcList = arcpy.ListFeatureClasses()
                outDirectory = os.path.join(root, 'shapefiles')
                print outDirectory
                if not os.path.isdir(outDirectory):
                    os.mkdir(outDirectory)
                    print 'Created -', outDirectory
                #for feature in fcList:
                arcpy.FeatureClassToShapefile_conversion(fcList, outDirectory)
Ejemplo n.º 19
0
def make_event_layer(in_table, out_shp):
    if not os.path.exists(os.path.dirname(out_shp)):
        os.mkdir(os.path.dirname(out_shp))
    if os.path.exists(out_shp):
        return
    x_coords = "Longitude"
    y_coords = "Latitude"
    spRef = r"D:/Dian/Spatial_Files/United_States_2000/background/Coordinate.prj"
    out_layer = os.path.basename(out_shp)[:-4]
    # saved_layer = out_shp[:-4]+".lyr"
    arcpy.MakeXYEventLayer_management(in_table, x_coords, y_coords, out_layer,
                                      spRef)
    # arcpy.SaveToLayerFile_management(out_layer, saved_layer)
    arcpy.FeatureClassToShapefile_conversion(out_layer,
                                             os.path.dirname(out_shp))
Ejemplo n.º 20
0
def getshapefile(infile):
    """Check type of input feature class, convert to shapefile if needed"""
    desc = arcpy.Describe(infile)
    if desc.datatype == "ShapeFile":
        return infile
    else:
        outshapefile = infile + ".shp"
        if arcpy.Exists(outshapefile) == True:
            return outshapefile
        else:
            try:
                outshapefile = infile + ".shp"
                arcpy.FeatureClassToShapefile_conversion(infile, outshapefile)
                return outshapefile
            except arcpy.ExecuteError:
                print(arcpy.GetMessages())
                return ""
Ejemplo n.º 21
0
def shapefile_conversion(file_list, csv_location, output_location, spatial_reference_code):
        """Takes a CSV as input, write a SHP as output"""
        arcpy.AddMessage("Converting to shapefile...")
        for file in file_list:
            csv_input = csv_location + r"\{0}".format(file)
            temp_layer = os.path.splitext(os.path.basename(csv_input))[0] # == "input"
            # Get NAD 1983 Alaska Albers Spatial reference
            prjfile = arcpy.SpatialReference(spatial_reference_code)
            arcpy.MakeXYEventLayer_management(csv_input, "long_site", "lat_site", temp_layer, prjfile)
            # exports a feature to a directory as a shapefile.
            # set covaraite shapefile feature class
            fc = os.path.join(output_location, temp_layer) + ".shp"
            # Delete covariate shapefile if exists
            if arcpy.Exists(fc):
                arcpy.Delete_management(fc)
            arcpy.FeatureClassToShapefile_conversion(temp_layer, output_location)
            arcpy.Delete_management(temp_layer) # clean up layer, for completeness
        arcpy.AddMessage("Shapefile conversion complete.")
Ejemplo n.º 22
0
def write_csv(parcels_intersect_index_fc, ml, countyName):
	'''Converts the polycount shapefile to a csv that get_count() will use'''
	
	#Getting vars for FeatureClassToShapefile_conversion
	parcel_intersect_index_csv = countyName + '_parcel_intersect_index.csv'
	Input_Features = parcels_intersect_index_fc.split('\\')[-1] #getting just the filename (poly_intersect_py_test_#) without the full path
	Output_Folder = "D:\\Data\\Poly_Count_Conversion"
	
	arcpy.FeatureClassToShapefile_conversion(Input_Features, Output_Folder)
	shapefile = Output_Folder + '\\' + Input_Features + '.shp'
	
	print("Converted Shapefile Layer")
	csv_file = arcpy.TableToTable_conversion(shapefile, Output_Folder, parcel_intersect_index_csv)

	print("This is the csv file: ", csv_file)
	print('CSV Conversion worked like a charm \n')

	return csv_file
Ejemplo n.º 23
0
def join_dati_e_salvataggio_shps():

    onlyfiles = [f for f in listdir(tab_loc) if isfile(join(tab_loc, f))]

    env.workspace = r"C:\data\tools\sparc\input_data\countries\countries.gdb"
    for fileggio in sorted(onlyfiles):
        fileName, fileExtension = path.splitext(fileggio)
        if fileExtension == '.dbf':
            for paese in sorted(paesi):
                paese_gdb = paese.split("_")[1]
                if fileName == paese_gdb:
                    loca_dbf = tab_loc + fileggio
                    loca_gdb = env.workspace + "/" + paese
                    print loca_dbf
                    print loca_gdb
                    linkata = arcpy.JoinField_management(
                        loca_gdb, "adm2_str", loca_dbf, "adm2_str")
                    arcpy.FeatureClassToShapefile_conversion(
                        loca_gdb, countries_dir)
Ejemplo n.º 24
0
def createFeatureClass(featureName, featureData, featureFieldList,
                       featureInsertCursorFields):
    print "Create " + featureName + " feature class"
    featureNameNAD83 = featureName + "_NAD83"
    featureNameNAD83Path = arcpy.env.workspace + "\\" + featureNameNAD83
    arcpy.CreateFeatureclass_management(arcpy.env.workspace, featureNameNAD83,
                                        "POINT", "", "DISABLED", "DISABLED",
                                        "", "", "0", "0", "0")
    # Process: Define Projection
    arcpy.DefineProjection_management(
        featureNameNAD83Path,
        "GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
    )
    # Process: Add Fields
    for featrueField in featureFieldList:
        arcpy.AddField_management(featureNameNAD83Path, featrueField[0],
                                  featrueField[1], featrueField[2],
                                  featrueField[3], featrueField[4],
                                  featrueField[5], featrueField[6],
                                  featrueField[7], featrueField[8])
    # Process: Append the records
    cntr = 1
    try:
        with arcpy.da.InsertCursor(featureNameNAD83,
                                   featureInsertCursorFields) as cur:
            for rowValue in featureData:
                cur.insertRow(rowValue)
                cntr = cntr + 1
    except Exception as e:
        print "\tError: " + featureName + ": " + e.message
    # Change the projection to web mercator
    arcpy.Project_management(
        featureNameNAD83Path, arcpy.env.workspace + "\\" + featureName,
        "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]",
        "NAD_1983_To_WGS_1984_5",
        "GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
    )
    arcpy.FeatureClassToShapefile_conversion([featureNameNAD83Path],
                                             OUTPUT_PATH + "\\Shapefile")
    arcpy.Delete_management(featureNameNAD83Path, "FeatureClass")
    print "Finish " + featureName + " feature class."
Ejemplo n.º 25
0
    arcpy.SelectLayerByLocation_management(ADA_Driveway_2036A0064Z,
                                           "INTERSECT", IOT2_Art_2036A0064Z,
                                           bridgebuffer, "NEW_SELECTION",
                                           "NOT_INVERT")

    # Process: Get Count (9)
    resultDriveway = arcpy.GetCount_management(ADA_Driveway_2036A0064Z__2_)
    count = int(resultDriveway.getOutput(0))
    print str(count) + " ADA driveways in " + trafCol_Num

    if count > 0:
        # Process: Table To Excel
        arcpy.TableToExcel_conversion(ADA_Driveway_2036A0064Z__2_,
                                      ADA_Driveway_2036A0064Z_xls, "NAME",
                                      "CODE")
        arcpy.FeatureClassToShapefile_conversion(ADA_Driveway_2036A0064Z,
                                                 Shapefiles)
        print "Exported driveways for " + trafCol_Num
    else:
        print "Did not export driveways for " + trafCol_Num

    # Process: Get Count (2)
    resultSidewalks = arcpy.GetCount_management(ADA_Sidewalks_2036A0064Z__2_)
    count = int(resultSidewalks.getOutput(0))
    print str(count) + " ADA sidewalks in " + trafCol_Num

    if count > 0:
        # Process: Table To Excel
        arcpy.TableToExcel_conversion(ADA_Sidewalks_2036A0064Z__2_,
                                      ADA_Sidewalks_2036A0064Z_xls, "NAME",
                                      "CODE")
        arcpy.FeatureClassToShapefile_conversion(ADA_Sidewalks_2036A0064Z,
Ejemplo n.º 26
0
    })

with open('JSON/{}.json'.format(nameCSV), "w") as f:
    json.dump(data, f)

df = pd.read_json('JSON/{}.json'.format(nameCSV))
df.to_csv('CSV/{}.csv'.format(nameCSV), index=None, encoding='utf-8')

# Set the local variables
in_Table = 'CSV/{}.csv'.format(nameCSV)
x_coords = "longitud"
y_coords = "latitud"
out_Layer = nameCSV

arcpy.MakeXYEventLayer_management(in_Table, x_coords, y_coords, out_Layer)
arcpy.FeatureClassToShapefile_conversion([out_Layer], r'SHP')
zfile = zipfile.ZipFile("SHP/{}.zip", format(nameCSV), "w", zipfile.ZIP_STORED)
files = os.listdir("SHP")
for f in files:
    if f.endswith("shp") or f.endswith("dbf") or f.endswith("shx"):
        zfile.write("SHP/" + f)

for f in zfile.namelist():
    print "Added %s" % f

zfile.close()

#**********************************************************************
# Description:
#    Zips the contents of a folder.
# Parameters:
Ejemplo n.º 27
0
arcpy.DefineProjection_management(mw_Source, "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.DefineProjection_management(mw_Pump, "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.DefineProjection_management(mw_Valve, "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.DefineProjection_management(mw_DemAlloc, "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.DefineProjection_management(mw_DemConn, "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")

# Process: Start Project features from Krovak to wgs84
print "Projecting to WGS84 coordinate system...";
arcpy.Project_management(mw_Junction, mw_Junction_out, "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]", "S_JTSK_To_WGS_1984_1", "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.Project_management(mw_Pipe, mw_Pipe_out, "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]", "S_JTSK_To_WGS_1984_1", "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.Project_management(mw_Tank, mw_Tank_out, "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]", "S_JTSK_To_WGS_1984_1", "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.Project_management(mw_Source, mw_Source_out, "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]", "S_JTSK_To_WGS_1984_1", "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.Project_management(mw_Pump, mw_Pump_out, "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]", "S_JTSK_To_WGS_1984_1", "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.Project_management(mw_Valve, mw_Valve_out, "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]", "S_JTSK_To_WGS_1984_1", "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.Project_management(mw_DemAlloc, mw_DemAlloc_out, "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]", "S_JTSK_To_WGS_1984_1", "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")
arcpy.Project_management(mw_DemConn, mw_DemConn_out, "PROJCS['WGS_1984_Web_Mercator_Auxiliary_Sphere',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator_Auxiliary_Sphere'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',0.0],PARAMETER['Standard_Parallel_1',0.0],PARAMETER['Auxiliary_Sphere_Type',0.0],UNIT['Meter',1.0]]", "S_JTSK_To_WGS_1984_1", "PROJCS['S-JTSK_Krovak_East_North',GEOGCS['GCS_S_JTSK',DATUM['D_S_JTSK',SPHEROID['Bessel_1841',6377397.155,299.1528128]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Krovak'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Pseudo_Standard_Parallel_1',78.5],PARAMETER['Scale_Factor',0.9999],PARAMETER['Azimuth',30.28813975277778],PARAMETER['Longitude_Of_Center',24.83333333333333],PARAMETER['Latitude_Of_Center',49.5],PARAMETER['X_Scale',-1.0],PARAMETER['Y_Scale',1.0],PARAMETER['XY_Plane_Rotation',90.0],UNIT['Meter',1.0]]")

print "Exporting final shapefiles of wgs84 coordinate system";
if not os.path.exists(Output+"\\SHP_WGS"):
    os.makedirs(Output+"\\SHP_WGS")
arcpy.FeatureClassToShapefile_conversion( mw_Junction_out, Output+"\\SHP_WGS")
arcpy.FeatureClassToShapefile_conversion(mw_Pipe_out, Output+"\\SHP_WGS")
arcpy.FeatureClassToShapefile_conversion(mw_Tank_out, Output+"\\SHP_WGS")
arcpy.FeatureClassToShapefile_conversion(mw_Source_out, Output+"\\SHP_WGS")
arcpy.FeatureClassToShapefile_conversion(mw_Pump_out, Output+"\\SHP_WGS")
arcpy.FeatureClassToShapefile_conversion(mw_Valve_out, Output+"\\SHP_WGS")
arcpy.FeatureClassToShapefile_conversion(mw_DemAlloc, Output+"\\SHP_WGS")
arcpy.FeatureClassToShapefile_conversion(mw_DemConn_out, Output+"\\SHP_WGS")

print "Done...";
Ejemplo n.º 28
0
if arcpy.Exists(startEndtemp) == True:
    arcpy.Delete_management(startEndtemp)

print "\nInfo: Data container is cleaned\n"

# Get geospatial geometries from Latitude and Longitude in data file, exported as point layer
arcpy.MakeXYEventLayer_management(smFilePath, smlatField, smlonField,
                                  smPointLyName, ukCoordSystem)

# Define the produced SMARTscan Input Features
smInputPoint = os.path.join(gdbDatabasePath, smPointLyName)
smOutputLine = os.path.join(gdbDatabasePath, smLineLyName)

# Get line layers and start & end node coordinate
arcpy.FeatureClassToShapefile_conversion(smPointLyName, gdbDatabasePath)
arcpy.PointsToLine_management(smInputPoint, smOutputLine, smlineField)

print "\nInfo: SMARTscan geospatial points and lines are produced"

# Get start node and end note layer
arcpy.AddGeometryAttributes_management(smOutputLine, "LINE_START_MID_END")
startLayer = arcpy.MakeXYEventLayer_management(smOutputLine, "START_X",
                                               "START_Y", "startLayer",
                                               ukCoordSystem)
endLayer = arcpy.MakeXYEventLayer_management(smOutputLine, "END_X", "END_Y",
                                             "endLayer", ukCoordSystem)

# Convert layer into geodatabase datafile
arcpy.FeatureClassToFeatureClass_conversion(startLayer, gdbDatabasePath,
                                            "StartEN")
Ejemplo n.º 29
0
        ])
    t.sleep(15)
    arcpy.SetProgressorPosition()

try:
    arcpy.SetProgressorLabel("Saving to {}.csv".format(time))
    col = [
        'callsign', 'lon', 'lat', 'geoaltitude', 'heading', 'icao24', 'time'
    ]
    data = pd.DataFrame(l, columns=col)
    data = data.drop_duplicates(subset=['callsign', 'lat', 'lon'])
    time = states.time
    #time = datetime.fromtimestamp(time).isoformat()
    file = csv_folder + "/{}.csv".format(str(time))
    data.to_csv(file, index=False)
    arcpy.SetProgressorPosition()
    arcpy.AddMessage("{}.csv".format(time))

    arcpy.SetProgressorLabel("Creating XY event")
    #layer = os.path.join(workspace,time)
    arcpy.MakeXYEventLayer_management(file, "lon", "lat", time)
    arcpy.FeatureClassToShapefile_conversion(time, shp_folder)
    arcpy.SetProgressorPosition()
    arcpy.AddMessage("Create XY event")

    shppath = shp_folder + shp(time)
    arcpy.MakeFeatureLayer_management(shppath, time)

except Exception:
    e = sys.exc_info()[1]
    arcpy.AddError(e.args[0])
Ejemplo n.º 30
0
nad83 = arcpy.SpatialReference()
nad83.factoryCode = 4269
nad83.create()
albers = arcpy.SpatialReference()
albers.factoryCode = 102039
albers.create()

# NHD variables:
flowline = os.path.join(nhd, "Hydrography", "NHDFlowline")
waterbody = os.path.join(nhd, "Hydrography", "NHDWaterbody")
network = os.path.join(nhd, "Hydrography", "HYDRO_NET")
junction = os.path.join(nhd, "Hydrography", "HYDRO_NET_Junctions")
arcpy.env.extent = waterbody

# Make shapefiles for one hectare and ten hectare lakes that intersect flowlines.
arcpy.FeatureClassToShapefile_conversion(waterbody, outfolder)
waterbodyshp = os.path.join(outfolder, "NHDWaterbody.shp")
arcpy.MakeFeatureLayer_management(waterbodyshp,
                                  os.path.join(outfolder, "waterbody.lyr"))
waterbody_lyr = os.path.join(outfolder, "waterbody.lyr")
arcpy.SelectLayerByAttribute_management(waterbody_lyr, "NEW_SELECTION",
                                        '''"AreaSqKm">=0.04''')
arcpy.SelectLayerByAttribute_management(
    waterbody_lyr, "SUBSET_SELECTION",
    '''"AreaSqKm" >=0.04 AND ("FCode" = 39000 OR "FCode" = 39004 OR\
"FCode" = 39009 OR "FCode" = 39010 OR "FCode" = 39011 OR "FCode" = 39012 OR "FCode" = 43600 OR "FCode" = 43613 OR\
"FCode" = 43615 OR "FCode" = 43617 OR "FCode" = 43618 OR "FCode" = 43619 OR "FCode" = 43621 OR ("FCode" = 43601 AND "AreaSqKm" >=0.1 ))'''
)
arcpy.CopyFeatures_management(waterbody_lyr,
                              os.path.join(outfolder, "all4ha.shp"))
all4ha = os.path.join(outfolder, "all4ha.shp")