Exemple #1
0
def layerToKml(outPath):
	ap.env.workspace = outPath
	pathLayer = outPath + "/out_final_mask_filter.shp"
	outKML = outPath + "/out_final_mask_filter_kml.kmz"
	ap.AddMessage("Converting to kml: "+ pathLayer)
	rasters = ap.ListRasters()
	inRaster = [img for img in rasters if 'out_final.img' in img]

	ap.LayerToKML_conversion(pathLayer, outKML)
	ap.AddMessage("Finished convert to kml")
def main():
    workspace = sys.argv[1]
    inputFeature = sys.argv[2]
    kmlFeature = sys.argv[3]
    scale = sys.argv[4]
    tempLyr = 'tempLyr.lyr'

    featureLyr = arcpy.MakeFeatureLayer_management(inputFeature, tempLyr)
    print('Temporary layer {} created'.format(tempLyr))
    arcpy.LayerToKML_conversion(tempLyr, kmlFeature, scale)
    print('{} created'.format(kmlFeature))
Exemple #3
0
def exportFCtoKML(vector):
    print '#############  create kmz  #################################'
    layer = "templayer"
    vector_kml = vector.replace('.shp', '.kmz')
    where_clause = "GRIDCODE = 3"
    arcpy.MakeFeatureLayer_management(vector, layer, where_clause)
    # arcpy.MakeFeatureLayer_management(vector, layer)
    arcpy.LayerToKML_conversion(layer, vector_kml)

    #### Delete layer after use
    arcpy.Delete_management(layer)
def make_kmz(layer, kmz_name, kmz_folder):
    if os.path.exists(layer):
        output_kmz = os.path.join(kmz_folder, kmz_name + '.kmz')
        if not os.path.exists(output_kmz):
            try:
                arcpy.LayerToKML_conversion(layer, output_kmz)
            except Exception as err:
                print err
        else:
            print '...Skipping ' + kmz_name + ': Already exists.'
    else:
        print '...Missing layer: ' + layer
Exemple #5
0
def covnertKMZ(a):

    env.workspace = "C:/Users/Noah/Desktop/grids/" + countyname + " County/shapefiles/{0}".format(
        a)

    infc = '{0}_fishnet_clip_4326.shp'.format(a)
    outfc = '{0}_fishnet.kmz'.format(a)
    fl = arcpy.MakeFeatureLayer_management(infc, "fishnet_lyr")
    arcpy.LayerToKML_conversion(fl, outfc)
    del infc
    del outfc
    arcpy.Delete_management(fl)
Exemple #6
0
 def kmz(self):
     kmz_file = self.full_path + '.kmz'
     arcpy.MakeFeatureLayer_management(self.shapefile, self.output_name)
     if arcpy.Exists(kmz_file):
         arcpy.Delete_management(kmz_file)
     try:
         arcpy.LayerToKML_conversion(self.output_name, kmz_file, '', '',
                                     self.output_name, '1024', '96',
                                     'CLAMPED_TO_GROUND')
         return True
     except Exception as err:
         AddMessage('Unable to export KMZ file: ' + str(err))
         return False
Exemple #7
0
def convert_to_kml(geodatabase):
    """Convert the contents of a geodatabase to KML.
    :param geodatabase: path to a geodatabase
    """
    import arcpy
    status_writer = status.Writer()
    arcpy.env.workspace = geodatabase
    arcpy.env.overwriteOutput = True
    feature_classes = arcpy.ListFeatureClasses()
    count = len(feature_classes)
    for i, fc in enumerate(feature_classes, 1):
        arcpy.MakeFeatureLayer_management(fc, "temp_layer")
        arcpy.LayerToKML_conversion("temp_layer", '{0}.kmz'.format(os.path.join(os.path.dirname(geodatabase), fc)), 1)
        status_writer.send_percent(float(i) / count, _('Converted: {0}').format(fc), 'convert_to_kml')
    arcpy.Delete_management("temp_layer")
Exemple #8
0
    def featureToKML():
        arcpy.env.workspace = defineGDBpath(['refinement','refinement'])
        # Use the ListFeatureClasses function to return a list of shapefiles.
        filename = "stco_*"
        featureclasses = arcpy.ListFeatureClasses(filename)

        # Copy shapefiles to a file geodatabase
        for fc in featureclasses:
            print fc

            # create directories to hold kml file and associated images
            stco_dir = rootpath + 'refinement/yfc/' + fc + '/'
            if not os.path.exists(stco_dir):
                os.makedirs(stco_dir)
            # Set local variables
            # Make a layer from the feature class
            arcpy.MakeFeatureLayer_management(fc,fc)

            out_kmz_file =  stco_dir + fc + '.kmz'
            arcpy.LayerToKML_conversion (fc, out_kmz_file)
Exemple #9
0
    def execute(self, parameters, messages):

        features = parameters[0].valueAsText
        feature_id_field = parameters[1].valueAsText
        out_ws = parameters[2].valueAsText

        feat_search_cursor = arcpy.da.SearchCursor(features,
                                                   [feature_id_field])

        for feat_row in feat_search_cursor:

            feat_id = feat_row[0].strip().replace(" ", "-")

            tmp_lyr = feat_id

            if arcpy.Exists(tmp_lyr):
                arcpy.Delete_management(tmp_lyr)

            where = "{} = '{}'".format(
                arcpy.AddFieldDelimiters(features, feature_id_field), feat_id)

            try:
                arcpy.MakeFeatureLayer_management(features, tmp_lyr, where)
                messages.addMessage(
                    "Temp layer for feature ID = {} created".format(feat_id))
            except Exception as e:
                messages.addWarningMessage(
                    "Could not create temp layer for feature ID = {}: {}".
                    format(feat_id, e))
                continue

# LayerToKML_conversion(layer, out_kmz_file, {layer_output_scale}, {is_composite}, {boundary_box_extent}, {image_size}, {dpi_of_client}, {ignore_zvalue})
            out_kmz = os.path.join(
                out_ws, "{}_{}_{}.kmz".format(features, feature_id_field,
                                              feat_id))
            arcpy.LayerToKML_conversion(tmp_lyr, out_kmz)
            arcpy.Delete_management(tmp_lyr)

            messages.addMessage("KML '{}' created".format(out_kmz))

        return
Exemple #10
0
    def _writeKMZ(self, fObject, name, folder):
        try:
            if self.overWriteOutput:
                filePath = os.path.join(folder, name + '.kmz')
                if arcpy.Exists(filePath): arcpy.Delete_management(filePath)
            else:
                filePath = arcpy.CreateScratchName(name, ".kmz", "", folder)

            Output_Layer = "extractFeatures_KMZ"
            if arcpy.Exists(Output_Layer):
                arcpy.Delete_management(Output_Layer)

            arcpy.MakeFeatureLayer_management(fObject.getFeatureSet(),
                                              Output_Layer)
            arcpy.LayerToKML_conversion(Output_Layer, filePath, "1000",
                                        "false", "DEFAULT", "1024", "96")
            arcpy.Delete_management(Output_Layer)

            return filePath
        except Exception, e:
            raise e
Exemple #11
0
def main():
    import arcpy
    import os
    arcpy.env.overwriteOutput = True

    # settings: edit these
    fc_in = r'C:\Users\Admin\Desktop\IDINSIGHTS-SHAPEFILES\All_Segments_Points.shp'
    fld_trail = 'clinic_nam'
    out_folder = r'C:\Users\Admin\Desktop\SettlementPoints'

    # create list of unique trail names
    lst_trails = list(
        set([r[0] for r in arcpy.da.SearchCursor(fc_in, (fld_trail))]))

    # loop through trails
    for trail_name in lst_trails:
        fld = arcpy.AddFieldDelimiters(fc_in, fld_trail)
        where = "{0} = '{1}'".format(fld, trail_name)
        arcpy.MakeFeatureLayer_management(fc_in, "Settlement_points", where)
        kmz_file = os.path.join(out_folder, "{0}.kmz".format(trail_name))
        arcpy.LayerToKML_conversion("Settlement_Points", kmz_file)
Exemple #12
0
    def featureToKML(wc):
        arcpy.env.workspace = defineGDBpath(['refinement','refinement'])
        # Use the ListFeatureClasses function to return a list of shapefiles.
        fc = arcpy.FeatureSet("combine_post_yfc_fc")
        # featureclasses = arcpy.ListFeatureClasses(filename)

        # Copy shapefiles to a file geodatabase
      

        # # create directories to hold kml file and associated images
        stco_dir = rootpath + 'refinement/yfc/gridcode_' + wc + '/'
        if not os.path.exists(stco_dir):
            os.makedirs(stco_dir)
        
        #Set local variables
        layer = "gridcode_" + wc
        where_clause = "gridcode = " + wc 

        # # Make a layer from the feature class
        arcpy.MakeFeatureLayer_management(fc, layer, where_clause)

        out_kmz_file =  stco_dir + 'gridcode_' + wc  + '.kmz'
        arcpy.LayerToKML_conversion(layer, out_kmz_file)
Exemple #13
0
def CreatingKML(fc, df, TaskMap, AssNum, output):
    try:
        if fc == "none":
            arcpy.AddWarning(
                "No features had this area name and no KML/KMZ created.")
        else:
            filekml = output + "/" + str(AssNum) + "_KML.kmz"
            fc_lyr = arcpy.mapping.Layer(fc)
            where4 = joinCheck("Area_Name", fc, df, TaskMap)
            arcpy.SelectLayerByAttribute_management(fc_lyr, "NEW_SELECTION",
                                                    where4)
            fc_lyr.visible = True
            arcpy.AddMessage("Creating KML/KMZ file for Assignment Number: " +
                             str(AssNum))
            arcpy.LayerToKML_conversion(fc_lyr,
                                        filekml,
                                        ignore_zvalue="CLAMPED_TO_GROUND")
            fc_lyr.visible = False
            arcpy.SelectLayerByAttribute_management(fc_lyr, "CLEAR_SELECTION")
    except:
        arcpy.AddWarning("Unable to produce KML/KMZ for Assignment: " + where4)
        pass
    return
Exemple #14
0
def KMLCreator(SLst, Wrkspc, IColor, Kname):
    arcpy.env.workspace = Wrkspc
    ColorRamp = IColor
    KmzName = Kname
    ListShp = SLst
    KmlFldr = os.path.join(Wrkspc, KmzName)

    if not os.path.exists(KmlFldr):
        os.makedirs(KmlFldr)

    KList = []
    for shp in ListShp:
        Var = "OV_INDEX"
        size = "1400"
        queryClause = Var + '>0'
        NwShp = shp.replace('prj', 'sel')
        NwShpPath = os.path.join(Wrkspc, NwShp)
        Kml = shp.replace('shp', 'kmz')
        Raster = shp.replace('shp', 'img')
        NwLyr = shp.replace('shp', 'lyr')
        SelectShp = arcpy.Select_analysis(shp, NwShpPath, queryClause)
        RasterImg = arcpy.PolygonToRaster_conversion(SelectShp, Var, Raster,
                                                     "CELL_CENTER", "NONE",
                                                     "14000")
        MKLyr = arcpy.MakeRasterLayer_management(
            RasterImg, NwLyr, "",
            "-13886732.4430092 2878561.3211416 -8916732.44300919 6280561.3211416",
            "")
        SymLyr = arcpy.ApplySymbologyFromLayer_management(MKLyr, ColorRamp)
        print(NwShpPath)
        KmlFile = os.path.join(KmlFldr, Kml)
        Klyr = arcpy.LayerToKML_conversion(SymLyr, KmlFile, "0",
                                           "NO_COMPOSITE", "DEFAULT", "1024",
                                           "96")
        KList.append(KmlFile)

    return KList, KmlFldr
Exemple #15
0
def export_kml():
    """Exports the feature class to a kml file
    
    Returns:
        None
    """
    arcpy.CheckOutExtension("3D")

    folder = 'kml'
    name = get_dataset_filename()

    # Create a kml folder in the temp directory if it does not exist
    temp_working_folder = os.path.join(temp_workspace, folder)
    create_folder(temp_working_folder, True)
    destination = os.path.join(temp_working_folder, name + ".kmz")

    # Make a feature layer (in memory)
    logger.debug('Generating KML file in memory from  "' +
                 staging_feature_class + '"')
    arcpy.MakeFeatureLayer_management(staging_feature_class, name, "", "")

    # Encode special characters that don't convert to KML correctly.
    # Replace any literal nulls <Null> with empty as these don't convert to KML correctly
    replace_literal_nulls(name)

    # Convert the layer to KML
    logger.debug('Exporting KML file (KMZ) to "' + destination + '"')
    arcpy.LayerToKML_conversion(name, destination, "20000", "false", "DEFAULT",
                                "1024", "96")

    # Delete the in-memory feature layer and the file geodatabase
    logger.debug('Deleting in-memory feature layer:' + name)
    arcpy.Delete_management(name)

    # Publish the zipfile to the download folder
    publish_file(temp_working_folder, name + ".kmz", "kml")
Exemple #16
0
def soil_to_kml(order_obj):
    soil_clip = os.path.join(config.scratch_folder, 'temp.gdb', "soil_clip")
    soil_mxd_path = os.path.join(config.scratch_folder, 'mxd_soil.mxd')
    if os.path.exists(soil_mxd_path):
        soil_mxd = arcpy.mapping.MapDocument(soil_mxd_path)
        df = arcpy.mapping.ListDataFrames(
            soil_mxd, "*"
        )[0]  # the spatial reference here is UTM zone #, need to change to WGS84 Web Mercator
        df.spatialReference = order_obj.spatial_ref_gcs
        if order_obj.province == 'AK':
            df.spatialReference = config.spatial_ref_mercator
        #re-focus using Buffer layer for multipage
        if config.if_multi_page == True:
            buffer_layer = arcpy.mapping.ListLayers(soil_mxd, "Buffer", df)[0]
            df.extent = buffer_layer.getSelectedExtent(False)
            df.scale = df.scale * 1.1
        df_as_feature = arcpy.Polygon(
            arcpy.Array([
                df.extent.lowerLeft, df.extent.lowerRight,
                df.extent.upperRight, df.extent.upperLeft
            ]), df.spatialReference)
        del df, soil_mxd

        arcpy.Project_management(
            df_as_feature,
            os.path.join(Kml_Config.viewer_temp, "Extent_soil_WGS84.shp"),
            order_obj.spatial_ref_gcs)
        arcpy.Clip_analysis(
            os.path.join(config.data_path_soil, 'MUPOLYGON'),
            os.path.join(Kml_Config.viewer_temp, "Extent_soil_WGS84.shp"),
            soil_clip)
        del df_as_feature

        if int(arcpy.GetCount_management(soil_clip).getOutput(0)) != 0:
            arcpy.AddField_management(soil_clip, "Map_Unit", "TEXT", "", "",
                                      "1500", "", "NULLABLE", "NON_REQUIRED",
                                      "")
            arcpy.AddField_management(soil_clip, "Map_Unit_Name", "TEXT", "",
                                      "", "1500", "", "NULLABLE",
                                      "NON_REQUIRED", "")
            arcpy.AddField_management(soil_clip, "Dominant_Drainage_Class",
                                      "TEXT", "", "", "1500", "", "NULLABLE",
                                      "NON_REQUIRED", "")
            arcpy.AddField_management(soil_clip, "Dominant_Hydrologic_Group",
                                      "TEXT", "", "", "1500", "", "NULLABLE",
                                      "NON_REQUIRED", "")
            arcpy.AddField_management(soil_clip,
                                      "Presence_Hydric_Classification", "TEXT",
                                      "", "", "1500", "", "NULLABLE",
                                      "NON_REQUIRED", "")
            arcpy.AddField_management(soil_clip, "Min_Bedrock_Depth", "TEXT",
                                      "", "", "1500", "", "NULLABLE",
                                      "NON_REQUIRED", "")
            arcpy.AddField_management(soil_clip, "Annual_Min_Watertable_Depth",
                                      "TEXT", "", "", "1500", "", "NULLABLE",
                                      "NON_REQUIRED", "")
            arcpy.AddField_management(soil_clip, "component", "TEXT", "", "",
                                      "2500", "", "NULLABLE", "NON_REQUIRED",
                                      "")
            arcpy.AddField_management(soil_clip, "ERISBIID", "TEXT", "", "",
                                      "15", "", "NULLABLE", "NON_REQUIRED", "")
            rows = arcpy.UpdateCursor(soil_clip)
            for row in rows:
                for map_unit in config.report_data:
                    if row.musym == map_unit["Musym"]:
                        id_final = [
                            id[1] for id in config.soil_ids
                            if row.MUSYM == id[0]
                        ]
                        if id_final != []:
                            row.ERISBIID = id_final[0]
                            rows.updateRow(row)
                        for key in map_unit.keys():
                            if key == "Musym":
                                row.Map_Unit = map_unit[key]
                            elif key == "Map Unit Name":
                                row.Map_Unit_Name = map_unit[key]
                            elif key == "Bedrock Depth - Min":
                                row.Min_Bedrock_Depth = map_unit[key]
                            elif key == "Drainage Class - Dominant":
                                row.Dominant_Drainage_Class = map_unit[key]
                            elif key == "Hydric Classification - Presence":
                                row.Presence_Hydric_Classification = map_unit[
                                    key]
                            elif key == "Hydrologic Group - Dominant":
                                row.Dominant_Hydrologic_Group = map_unit[key]
                            elif key == "Watertable Depth - Annual Min":
                                row.Annual_Min_Watertable_Depth = map_unit[key]
                            elif key == "component":
                                new = ''
                                component = map_unit[key]
                                for i in range(len(component)):
                                    for j in range(len(component[i])):
                                        for k in range(len(component[i][j])):
                                            new = new + component[i][j][k] + " "
                                row.component = new
                            else:
                                pass
                            rows.updateRow(row)
            del rows
            keep_field_list = ("ERISBIID", "Map_Unit", "Map_Unit_Name",
                               "Dominant_Drainage_Class",
                               "Dominant_Hydrologic_Group",
                               "Presence_Hydric_Classification",
                               "Min_Bedrock_Depth",
                               "Annual_Min_Watertable_Depth", "component")
            field_info = ""
            fieldList = arcpy.ListFields(soil_clip)
            for field in fieldList:
                if field.name in keep_field_list:
                    if field.name == 'ERISBIID':
                        field_info = field_info + field.name + " " + "ERISBIID" + " VISIBLE;"
                    elif field.name == 'Map_Unit':
                        field_info = field_info + field.name + " " + "Map_Unit" + " VISIBLE;"
                    elif field.name == 'Map_Unit_Name':
                        field_info = field_info + field.name + " " + "Map_Unit_Name" + " VISIBLE;"
                    elif field.name == 'Dominant_Drainage_Class':
                        field_info = field_info + field.name + " " + "Dominant_Drainage_Class" + " VISIBLE;"
                    elif field.name == 'Dominant_Hydrologic_Group':
                        field_info = field_info + field.name + " " + "Dominant_Hydrologic_Group" + " VISIBLE;"
                    elif field.name == 'Presence_Hydric_Classification':
                        field_info = field_info + field.name + " " + "Presence_Hydric_Classification" + " VISIBLE;"
                    elif field.name == 'Min_Bedrock_Depth':
                        field_info = field_info + field.name + " " + "Min_Bedrock_Depth" + " VISIBLE;"
                    elif field.name == 'Annual_Min_Watertable_Depth':
                        field_info = field_info + field.name + " " + "Annual_Min_Watertable_Depth" + " VISIBLE;"
                    elif field.name == 'component':
                        field_info = field_info + field.name + " " + "component" + " VISIBLE;"
                    else:
                        pass
                else:
                    field_info = field_info + field.name + " " + field.name + " HIDDEN;"
            arcpy.MakeFeatureLayer_management(soil_clip, 'soil_clip_lyr', "",
                                              "", field_info[:-1])
            soil_symbol_local = os.path.join(config.scratch_folder,
                                             "soil_lyr_local.lyr")
            arcpy.SaveToLayerFile_management(config.soil_lyr,
                                             soil_symbol_local[:-4])
            arcpy.ApplySymbologyFromLayer_management('soil_clip_lyr',
                                                     soil_symbol_local)
            arcpy.LayerToKML_conversion(
                'soil_clip_lyr',
                os.path.join(Kml_Config.viewer_dir_kml, "soil_clip.kmz"))
            arcpy.Delete_management('soil_clip_lyr')
        else:
            arcpy.AddMessage('no soil data to kml')
            arcpy.MakeFeatureLayer_management(soil_clip, 'soil_clip_lyr')
            arcpy.LayerToKML_conversion(
                'soil_clip_lyr',
                os.path.join(Kml_Config.viewer_dir_kml,
                             "soil_clip_nodata.kmz"))
            arcpy.AddMessage('      -- Create soil kmz map: %s' % os.path.join(
                Kml_Config.viewer_dir_kml, "soil_clip_nodata.kmz"))
            arcpy.Delete_management('soil_clip_lyr')
    else:
        arcpy.AddMessage(
            '  -- Soil report is not generatated therfore the soil kml file cannot be exported.'
        )
        #If it is after the first iteration then the raster addition function will be used.
        if x >= 1:
            #This labels the Output_Raster with the number of the iteration. 
            Output_Raster= "Out_Ras" + str(x)
            #This is the raster addition function, it takes the last value in both the main_list and temp_list and sums them.
            outPlus= Raster(main_list[-1])+Raster(temp_list[-1])
            outPlus.save(Output_Raster)
            #This takes the sum above and appends it to the main_list to be used in the raster addition function in the next iteration.
            main_list.append(Output_Raster)
        #This adds one to the iteration counter.
        x= x+1

#Reclassify the last Output_Raster, which is the sum of all the rasters, to make sure the output is in a unique values.
Reclass= Reclassify(Output_Raster, "Value", RemapValue([[-1,0,0],[0,1,1],[1,2,2],[2,3,3],[3,4,4],[4,5,5],[5,6,6],[6,7,7],[7,8,8],[8,9,9],[9,10,10],[10,11,11],[11,12,12],[12,13,13],[13,14,14],[14,15,15],[15,16,16],[16,17,17],[17,18,18],[18,19,19],[19,20,20],[20,21,21],[21,22,22],[22,23,23],[23,24,24],[24,25,25],[25,26,26],[26,27,27],[27,28,28],[28,29,29],[29,30,30],[30,31,31],[31,32,32],[32,33,33],[33,34,34],[34,35,35],[35,36,36],[36,37,37],[37,38,38],[38,39,39],[39,40,40],[40,41,41]]))
Reclass.save(Reclass_Output)

#Reclassify again, this time valuing -1 to 0 as No Data.
Reclass2= Reclassify(Reclass_Output, "Value", RemapValue([[-1,0,"NoData"],[0,1,1],[1,2,2],[2,3,3],[3,4,4],[4,5,5],[5,6,6],[6,7,7],[7,8,8],[8,9,9],[9,10,10],[10,11,11],[11,12,12],[12,13,13],[13,14,14],[14,15,15],[15,16,16],[16,17,17],[17,18,18],[18,19,19],[19,20,20],[20,21,21],[21,22,22],[22,23,23],[23,24,24],[24,25,25],[25,26,26],[26,27,27],[27,28,28],[28,29,29],[29,30,30],[30,31,31],[31,32,32],[32,33,33],[33,34,34],[34,35,35],[35,36,36],[36,37,37],[37,38,38],[38,39,39],[39,40,40],[40,41,41]]))
Reclass2.save("DEL_Reclass")

#Convert raster to polygon in order to make kmz.
Polygon= "Freq.shp"
arcpy.RasterToPolygon_conversion("DEL_Reclass", Polygon, "NO_SIMPLIFY", "VALUE")
    
#Make Feature Layer
Del= Kmz_Name
arcpy.MakeFeatureLayer_management(Polygon, Del)

#Convert layer to kmz
arcpy.LayerToKML_conversion(Del, Kmz_Var)
Exemple #18
0
def convert_to_kml(input_items, out_workspace, extent, show_progress=False):
    converted = 0
    errors = 0
    skipped = 0
    global processed_count
    global layer_name
    global existing_fields
    global new_fields
    global field_values

    arcpy.env.overwriteOutput = True
    for ds, out_name in input_items.iteritems():
        try:
            # -----------------------------------------------
            # If the item is a service layer, process and continue.
            # -----------------------------------------------
            if ds.startswith('http'):
                try:
                    service_layer = task_utils.ServiceLayer(
                        ds, extent.JSON, 'esriGeometryPolygon')
                    arcpy.env.overwriteOutput = True
                    oid_groups = service_layer.object_ids
                    out_features = None
                    g = 0.
                    group_cnt = service_layer.object_ids_cnt
                    if not arcpy.Exists(os.path.join(out_workspace,
                                                     'temp.gdb')):
                        temp_gdb = arcpy.CreateFileGDB_management(
                            out_workspace, 'temp.gdb')
                        temp_gdb = temp_gdb[0]
                    else:
                        temp_gdb = os.path.join(out_workspace, 'temp.gdb')
                    for group in oid_groups:
                        g += 1
                        group = [oid for oid in group if oid]
                        where = '{0} IN {1}'.format(
                            service_layer.oid_field_name, tuple(group))
                        url = ds + "/query?where={}&outFields={}&returnGeometry=true&f=json&".format(
                            where, '*')
                        feature_set = arcpy.FeatureSet()
                        try:
                            feature_set.load(url)
                        except Exception:
                            continue
                        if not out_features:
                            out_features = arcpy.CopyFeatures_management(
                                feature_set,
                                task_utils.create_unique_name(
                                    out_name, temp_gdb))
                        else:
                            features = arcpy.CopyFeatures_management(
                                feature_set,
                                task_utils.create_unique_name(
                                    out_name, temp_gdb))
                            arcpy.Append_management(features, out_features,
                                                    'NO_TEST')
                            try:
                                arcpy.Delete_management(features)
                            except arcpy.ExecuteError:
                                pass
                        status_writer.send_percent(
                            float(g) / group_cnt * 100, '', 'convert_to_kml')
                    arcpy.MakeFeatureLayer_management(out_features, out_name)
                    arcpy.LayerToKML_conversion(
                        out_name,
                        '{0}.kmz'.format(os.path.join(out_workspace,
                                                      out_name)),
                        1,
                        boundary_box_extent=extent)
                    processed_count += 1.
                    converted += 1
                    status_writer.send_percent(processed_count / result_count,
                                               _('Converted: {0}').format(ds),
                                               'convert_to_kml')
                    continue
                except Exception as ex:
                    status_writer.send_state(status.STAT_WARNING, str(ex))
                    errors += 1
                    errors_reasons[ds] = ex.message
                    continue

            # Is the input a mxd data frame.
            map_frame_name = task_utils.get_data_frame_name(ds)
            if map_frame_name:
                ds = ds.split('|')[0].strip()

            # -------------------------------
            # Is the input a geometry feature
            # -------------------------------
            if isinstance(out_name, list):
                increment = task_utils.get_increment(result_count)
                for row in out_name:
                    try:
                        name = arcpy.ValidateTableName(ds, 'in_memory')
                        name = os.path.join('in_memory', name)
                        # Clip the geometry.
                        geo_json = row['[geo]']
                        geom = arcpy.AsShape(geo_json)
                        row.pop('[geo]')
                        if not arcpy.Exists(name):
                            if arcpy.env.outputCoordinateSystem:
                                layer_name = arcpy.CreateFeatureclass_management(
                                    'in_memory', os.path.basename(name),
                                    geom.type.upper())
                            else:
                                arcpy.env.outputCoordinateSystem = 4326
                                layer_name = arcpy.CreateFeatureclass_management(
                                    'in_memory', os.path.basename(name),
                                    geom.type.upper())
                            # layer_name = arcpy.MakeFeatureLayer_management(name, 'flayer')
                            existing_fields = [
                                f.name for f in arcpy.ListFields(layer_name)
                            ]
                            new_fields = []
                            field_values = []
                            for field, value in row.iteritems():
                                valid_field = arcpy.ValidateFieldName(
                                    field, 'in_memory')
                                new_fields.append(valid_field)
                                field_values.append(value)
                                arcpy.AddField_management(
                                    layer_name, valid_field, 'TEXT')
                        else:
                            if not geom.type.upper() == arcpy.Describe(
                                    name).shapeType.upper():
                                name = arcpy.CreateUniqueName(
                                    os.path.basename(name), 'in_memory')
                                if arcpy.env.outputCoordinateSystem:
                                    layer_name = arcpy.CreateFeatureclass_management(
                                        'in_memory', os.path.basename(name),
                                        geom.type.upper())
                                else:
                                    arcpy.env.outputCoordinateSystem = 4326
                                    layer_name = arcpy.CreateFeatureclass_management(
                                        'in_memory', os.path.basename(name),
                                        geom.type.upper())

                                existing_fields = [
                                    f.name
                                    for f in arcpy.ListFields(layer_name)
                                ]
                                new_fields = []
                                field_values = []
                                for field, value in row.iteritems():
                                    valid_field = arcpy.ValidateFieldName(
                                        field, 'in_memory')
                                    new_fields.append(valid_field)
                                    field_values.append(value)
                                    if not valid_field in existing_fields:
                                        arcpy.AddField_management(
                                            layer_name, valid_field, 'TEXT')

                        with arcpy.da.InsertCursor(layer_name, ["SHAPE@"] +
                                                   new_fields) as icur:
                            icur.insertRow([geom] + field_values)

                        arcpy.MakeFeatureLayer_management(
                            layer_name, os.path.basename(name))
                        arcpy.LayerToKML_conversion(
                            os.path.basename(name),
                            '{0}.kmz'.format(
                                os.path.join(out_workspace,
                                             os.path.basename(name))),
                            1,
                            boundary_box_extent=extent)
                        if (processed_count % increment) == 0:
                            status_writer.send_percent(
                                float(processed_count) / result_count,
                                _('Converted: {0}').format(row['name']),
                                'convert_to_kml')
                        processed_count += 1
                        converted += 1
                    except KeyError:
                        processed_count += 1
                        skipped += 1
                        skipped_reasons[ds] = 'Invalid input type'
                        status_writer.send_state(
                            _(status.STAT_WARNING,
                              'Invalid input type: {0}').format(ds))
                    except Exception as ex:
                        processed_count += 1
                        errors += 1
                        errors_reasons[ds] = ex.message
                        continue
                del icur
                continue

            dsc = arcpy.Describe(ds)

            if os.path.exists(
                    os.path.join('{0}.kmz'.format(
                        os.path.join(out_workspace, out_name)))):
                out_name = os.path.basename(
                    arcpy.CreateUniqueName(out_name + '.kmz',
                                           out_workspace))[:-4]

            if dsc.dataType == 'FeatureClass':
                arcpy.MakeFeatureLayer_management(ds, dsc.name)
                if out_name == '':
                    out_name = dsc.name
                arcpy.LayerToKML_conversion(
                    dsc.name,
                    '{0}.kmz'.format(os.path.join(out_workspace, out_name)),
                    1,
                    boundary_box_extent=extent)
                converted += 1

            elif dsc.dataType == 'ShapeFile':
                arcpy.MakeFeatureLayer_management(ds, dsc.name[:-4])
                if out_name == '':
                    out_name = dsc.name[:-4]
                arcpy.LayerToKML_conversion(
                    dsc.name[:-4],
                    '{0}.kmz'.format(os.path.join(out_workspace, out_name)),
                    1,
                    boundary_box_extent=extent)
                converted += 1

            elif dsc.dataType == 'RasterDataset':
                arcpy.MakeRasterLayer_management(ds, dsc.name)
                if out_name == '':
                    out_name = dsc.name
                arcpy.LayerToKML_conversion(
                    dsc.name,
                    '{0}.kmz'.format(os.path.join(out_workspace, out_name)),
                    1,
                    boundary_box_extent=extent)
                converted += 1

            elif dsc.dataType == 'Layer':
                if out_name == '':
                    if dsc.name.endswith('.lyr'):
                        out_name = dsc.name[:-4]
                    else:
                        out_name = dsc.name
                arcpy.LayerToKML_conversion(
                    ds,
                    '{0}.kmz'.format(os.path.join(out_workspace, out_name)),
                    1,
                    boundary_box_extent=extent)
                converted += 1

            elif dsc.dataType == 'FeatureDataset':
                arcpy.env.workspace = ds
                for fc in arcpy.ListFeatureClasses():
                    arcpy.MakeFeatureLayer_management(fc, 'tmp_lyr')
                    arcpy.LayerToKML_conversion(
                        'tmp_lyr',
                        '{0}.kmz'.format(os.path.join(out_workspace, fc)),
                        1,
                        boundary_box_extent=extent)
                    converted += 1

            elif dsc.dataType == 'CadDrawingDataset':
                arcpy.env.workspace = dsc.catalogPath
                for cad_fc in arcpy.ListFeatureClasses():
                    if cad_fc.lower() == 'annotation':
                        try:
                            cad_anno = arcpy.ImportCADAnnotation_conversion(
                                cad_fc,
                                arcpy.CreateUniqueName('cadanno',
                                                       arcpy.env.scratchGDB))
                        except arcpy.ExecuteError:
                            cad_anno = arcpy.ImportCADAnnotation_conversion(
                                cad_fc,
                                arcpy.CreateUniqueName('cadanno',
                                                       arcpy.env.scratchGDB),
                                1)
                        arcpy.MakeFeatureLayer_management(cad_anno, 'cad_lyr')
                        name = '{0}_{1}'.format(dsc.name[:-4], cad_fc)
                        arcpy.LayerToKML_conversion(
                            'cad_lyr',
                            '{0}.kmz'.format(os.path.join(out_workspace,
                                                          name)),
                            1,
                            boundary_box_extent=extent)
                        converted += 1
                    else:
                        arcpy.MakeFeatureLayer_management(cad_fc, 'cad_lyr')
                        name = '{0}_{1}'.format(dsc.name[:-4], cad_fc)
                        arcpy.LayerToKML_conversion(
                            'cad_lyr',
                            '{0}.kmz'.format(os.path.join(out_workspace,
                                                          name)),
                            1,
                            boundary_box_extent=extent)
                        converted += 1

            # Map document to KML.
            elif dsc.dataType == 'MapDocument':
                mxd = arcpy.mapping.MapDocument(ds)
                if map_frame_name:
                    data_frames = arcpy.mapping.ListDataFrames(
                        mxd, map_frame_name)
                else:
                    data_frames = arcpy.mapping.ListDataFrames(mxd)
                for df in data_frames:
                    name = '{0}_{1}'.format(dsc.name[:-4], df.name)
                    arcpy.MapToKML_conversion(
                        ds,
                        df.name,
                        '{0}.kmz'.format(os.path.join(out_workspace, name)),
                        extent_to_export=extent)
                converted += 1

            else:
                processed_count += 1
                status_writer.send_percent(
                    processed_count / result_count,
                    _('Invalid input type: {0}').format(dsc.name),
                    'convert_to_kml')
                skipped += 1
                skipped_reasons[ds] = _('Invalid input type: {0}').format(
                    dsc.dataType)
                continue
            processed_count += 1
            status_writer.send_percent(processed_count / result_count,
                                       _('Converted: {0}').format(ds),
                                       'convert_to_kml')
            status_writer.send_status(_('Converted: {0}').format(ds))
        except Exception as ex:
            processed_count += 1
            status_writer.send_percent(processed_count / result_count,
                                       _('Skipped: {0}').format(ds),
                                       'convert_to_kml')
            status_writer.send_status(_('WARNING: {0}').format(repr(ex)))
            errors_reasons[ds] = repr(ex)
            errors += 1
            pass

    return converted, errors, skipped
Exemple #19
0
def extract(input_items, out_type, output_dir):
    """Extract geographic information from input items."""
    extracted = 0
    skipped = 0
    errors = 0
    global processed_count

    # Get the LocateXT GP Toolbox
    for src_file in input_items:
        processed_count += 1
        try:
            if os.path.isfile(src_file):
                file_name = arcpy.ValidateTableName(
                    os.path.basename(os.path.splitext(src_file)[0]))
                if out_type == 'CSV':
                    shp_file = os.path.join(output_dir,
                                            '{0}.shp'.format(file_name))
                    arcpy.LocateXT_Tool_lxt(src_file, shp_file)
                    xls_file = os.path.join(output_dir,
                                            '{0}.xls'.format(file_name))
                    arcpy.TableToExcel_conversion(shp_file, xls_file)
                    xls_to_csv(xls_file)
                    arcpy.Delete_management(shp_file)
                    arcpy.Delete_management(xls_file)
                elif out_type == 'KML':
                    shp_file = os.path.join(output_dir,
                                            '{0}.shp'.format(file_name))
                    arcpy.LocateXT_Tool_lxt(src_file, shp_file)
                    layer_name = os.path.basename(shp_file)[:-4]
                    arcpy.MakeFeatureLayer_management(shp_file, layer_name)
                    arcpy.LayerToKML_conversion(
                        layer_name,
                        '{0}.kmz'.format(os.path.join(output_dir,
                                                      layer_name)), 1)
                    arcpy.Delete_management(shp_file)
                elif out_type == 'SHP':
                    arcpy.LocateXT_Tool_lxt(
                        src_file,
                        os.path.join(output_dir, '{0}.shp'.format(file_name)))
                elif out_type == 'FGDB':
                    arcpy.LocateXT_Tool_lxt(
                        src_file,
                        os.path.join(output_dir, 'output.gdb', file_name))

                status_writer.send_percent(
                    processed_count / result_count,
                    _('Extracted: {0}').format(src_file),
                    'locate_xt_arcgis_tool')
                extracted += 1
            else:
                status_writer.send_percent(
                    processed_count / result_count,
                    _('{0} is not a supported file type or does no exist').
                    format(src_file), 'locate_xt_arcgis_tool')
                skipped += 1
                skipped_reasons[src_file] = _(
                    '{0} is not a supported file type or does no exist'
                ).format(os.path.basename(src_file))
        except IOError as io_err:
            status_writer.send_percent(processed_count / result_count,
                                       _('Skipped: {0}').format(src_file),
                                       'locate_xt_arcgis_tool')
            status_writer.send_status(_('FAIL: {0}').format(repr(io_err)))
            errors += 1
            errors_reasons[src_file] = repr(io_err)
            pass
        except arcpy.ExecuteError:
            status_writer.send_status(
                _('FAIL: {0}').format(arcpy.GetMessages(2)))
            errors += 1
            errors_reasons[src_file] = arcpy.GetMessages(2)
            pass
    return extracted, errors, skipped
Exemple #20
0
def wetland_to_kml(order_obj):
    wetland_clip = os.path.join(config.scratch_folder, "wetland_clip.shp")
    wetland_mxd_path = os.path.join(config.scratch_folder, 'mxd_wetland.mxd')
    if os.path.exists(wetland_mxd_path):
        wetland_mxd = arcpy.mapping.MapDocument(wetland_mxd_path)
        df = arcpy.mapping.ListDataFrames(
            wetland_mxd, "big"
        )[0]  # the spatial reference here is UTM zone #, need to change to WGS84 Web Mercator
        df.spatialReference = order_obj.spatial_ref_gcs
        if order_obj.province == 'AK':
            df.spatialReference = config.spatial_ref_mercator
        #re-focus using Buffer layer for multipage
        if config.if_multi_page == True:
            buffer_layer = arcpy.mapping.ListLayers(wetland_mxd, "Buffer",
                                                    df)[0]
            df.extent = buffer_layer.getSelectedExtent(False)
            df.scale = df.scale * 1.1
        #df.spatialReference is currently UTM. dfAsFeature is a feature, not even a layer
        df_as_feature = arcpy.Polygon(
            arcpy.Array([
                df.extent.lowerLeft, df.extent.lowerRight,
                df.extent.upperRight, df.extent.upperLeft
            ]), df.spatialReference)
        del df, wetland_mxd
        wetland_boudnary = os.path.join(config.scratch_folder,
                                        "wetland_kml_extend.shp")
        arcpy.Project_management(df_as_feature, wetland_boudnary,
                                 order_obj.spatial_ref_gcs)
        arcpy.Clip_analysis(config.data_lyr_wetland, wetland_boudnary,
                            wetland_clip)
        del df_as_feature

        wetland_clip_final = None
        if int(arcpy.GetCount_management(wetland_clip).getOutput(0)) != 0:
            arcpy.AddField_management(wetland_boudnary, "TYPE", "TEXT", "", "",
                                      "15", "", "NULLABLE", "NON_REQUIRED", "")
            wetland_clip_final = os.path.join(config.scratch_folder,
                                              "wetland_clip_final.shp")
            arcpy.Union_analysis([wetland_clip, wetland_boudnary],
                                 wetland_clip_final)

            keepFieldList = ("TYPE")
            fieldInfo = ""
            fieldList = arcpy.ListFields(wetland_clip_final)
            for field in fieldList:
                if field.name in keepFieldList:
                    if field.name == 'TYPE':
                        fieldInfo = fieldInfo + field.name + " " + "Wetland Type" + " VISIBLE;"
                    else:
                        pass
                else:
                    fieldInfo = fieldInfo + field.name + " " + field.name + " HIDDEN;"

            arcpy.MakeFeatureLayer_management(wetland_clip_final,
                                              'wetland_clip_lyr', "", "",
                                              fieldInfo[:-1])
            arcpy.ApplySymbologyFromLayer_management('wetland_clip_lyr',
                                                     config.data_lyr_wetland)
            arcpy.LayerToKML_conversion(
                'wetland_clip_lyr',
                os.path.join(Kml_Config.viewer_dir_kml, "wetland.kmz"))
            arcpy.AddMessage(
                '      -- Create Wetland kmz map: %s' %
                os.path.join(Kml_Config.viewer_dir_kml, "wetland.kmz"))
            arcpy.Delete_management('wetland_clip_lyr')
        else:
            arcpy.AddMessage('      -- no wetland data')
            arcpy.MakeFeatureLayer_management(wetland_clip, 'wetland_clip_lyr')
            arcpy.LayerToKML_conversion(
                'wetland_clip_lyr',
                os.path.join(Kml_Config.viewer_dir_kml, "wetland_nodata.kmz"))
            arcpy.AddMessage(
                '      -- Create Wetland kmz map: %s' %
                os.path.join(Kml_Config.viewer_dir_kml, "wetland_nodata.kmz"))
            arcpy.Delete_management('wetland_clip_lyr')
    else:
        arcpy.AddMessage(
            '  -- Wetland report is not generatated therfore the wetland kml file cannot be exported.'
        )
Exemple #21
0
import os
import arcpy

arcpy.env.overwriteOutput = True
path = r'D:\temp'  # Cambiar lo que esta entre comillas por tu carpeta
BASE_DIR = os.path.join(path)
listpaths = [
    os.path.join(BASE_DIR, x) for x in os.listdir(BASE_DIR)
    if x.split(".")[-1] == "shp"
]
for x in listpaths:
    print x
    mfl = arcpy.MakeFeatureLayer_management(x, "mfl")
    arcpy.LayerToKML_conversion(mfl, x.split(".")[-2] + ".kmz")
Exemple #22
0
#batch conversion of shapefile features into google earth kml format
import arcpy

arcpy.env.workspace = r'set your workspace'
workspace = arcpy.env.workspace
Features = ["fill in with your features"]
#first to layers
for feature in Features:
    print type(feature)
    outlayer = feature + ".lyr"
    arcpy.SaveToLayerFile_management(feature, outlayer, "ABSOLUTE")

#list .lyr's
layers = arcpy.ListFiles("*.lyr*")
#then to kml || kmz
for layer in layers:
    oName, oExt = os.path.splitext(layer)
    outKML = oName + ".kmz"
    arcpy.LayerToKML_conversion(layer, outKML)
Exemple #23
0
import arcpy
import os

arcpy.env.workspace = "C:\\859K_sl559\\Scratch5"

# Set Local Variables
composite = 'NO_COMPOSITE'
pixels = 2048
dpi = 96
clamped = 'CLAMPED_TO_GROUND'

# Use the ListFiles method to identify all lyr and lyrx files in workspace
layers = arcpy.ListFiles("*.shp*")

if len(layers) > 0:
    for layer in layers:
        # Strips the '.lyr(x)' part of the name and appends '.kmz'
        outKML = "test1" + ".kmz"
        for scale in range(10000, 30001, 10000):
            # Execute LayerToKML
            arcpy.LayerToKML_conversion(layer, outKML, scale, composite, '',
                                        pixels, dpi, clamped)
else:
    arcpy.AddMessage('There are no layer files in {}'.format(
        arcpy.env.workspace))
Exemple #24
0
def flood_to_kml(order_obj):
    if os.path.exists(config.flood_selectedby_order_shp):
        if int(
                arcpy.GetCount_management(
                    config.flood_selectedby_order_shp).getOutput(0)) != 0:
            arcpy.AddField_management(config.flood_selectedby_order_shp,
                                      "CLASS", "TEXT", "", "", "15", "",
                                      "NULLABLE", "NON_REQUIRED", "")
            arcpy.AddField_management(config.flood_selectedby_order_shp,
                                      "ERISBIID", "TEXT", "", "", "15", "",
                                      "NULLABLE", "NON_REQUIRED", "")
            rows = arcpy.UpdateCursor(config.flood_selectedby_order_shp)
            for row in rows:
                row.CLASS = row.ERIS_CLASS
                ID = [
                    id[1] for id in config.flood_ids if row.ERIS_CLASS == id[0]
                ]
                if ID != []:
                    row.ERISBIID = ID[0]
                    rows.updateRow(row)
                rows.updateRow(row)
            del rows
            keep_field_list = ("ERISBIID", "CLASS", "FLD_ZONE", "ZONE_SUBTY")
            field_info = ""
            field_list = arcpy.ListFields(config.flood_selectedby_order_shp)
            for field in field_list:
                if field.name in keep_field_list:
                    if field.name == 'ERISBIID':
                        field_info = field_info + field.name + " " + "ERISBIID" + " VISIBLE;"
                    elif field.name == 'CLASS':
                        field_info = field_info + field.name + " " + "Flood Zone Label" + " VISIBLE;"
                    elif field.name == 'FLD_ZONE':
                        field_info = field_info + field.name + " " + "Flood Zone" + " VISIBLE;"
                    elif field.name == 'ZONE_SUBTY':
                        field_info = field_info + field.name + " " + "Zone Subtype" + " VISIBLE;"
                    else:
                        pass
                else:
                    field_info = field_info + field.name + " " + field.name + " HIDDEN;"
            arcpy.MakeFeatureLayer_management(
                config.flood_selectedby_order_shp, 'selected_flood_data_lyr',
                "", "", field_info[:-1])
            arcpy.ApplySymbologyFromLayer_management('selected_flood_data_lyr',
                                                     config.data_lyr_flood)
            arcpy.LayerToKML_conversion(
                'selected_flood_data_lyr',
                os.path.join(Kml_Config.viewer_dir_kml, "flood.kmz"))
            arcpy.AddMessage(
                '      -- Create flood kmz map: %s' %
                os.path.join(Kml_Config.viewer_dir_kml, "flood.kmz"))
            arcpy.Delete_management('selected_flood_data_lyr')
        else:
            arcpy.AddMessage('no flood data to kml')
            arcpy.MakeFeatureLayer_management(
                config.flood_selectedby_order_shp, 'selected_flood_data_lyr')
            arcpy.LayerToKML_conversion(
                'selected_flood_data_lyr',
                os.path.join(Kml_Config.viewer_dir_kml, "flood_nodata.kmz"))
            arcpy.AddMessage(
                '      -- Create flood kmz map: %s' %
                os.path.join(Kml_Config.viewer_dir_kml, "flood_nodata.kmz"))
            arcpy.Delete_management('selected_flood_data_lyr')
    else:
        arcpy.AddMessage(
            '  -- Flood report is not generatated therfore the flood kml file cannot be exported.'
        )
Exemple #25
0
def geology_to_kml(order_obj):
    geology_clip = os.path.join(config.scratch_folder, "geology_clip.shp")
    geology_mxd_path = os.path.join(config.scratch_folder, 'mxd_geology.mxd')
    if os.path.exists(geology_mxd_path):
        geology_mxd = arcpy.mapping.MapDocument(geology_mxd_path)
        df = arcpy.mapping.ListDataFrames(
            geology_mxd, "*"
        )[0]  # the spatial reference here is UTM zone #, need to change to WGS84 Web Mercator
        df.spatialReference = order_obj.spatial_ref_gcs
        if order_obj.province == 'AK':
            df.spatialReference = config.spatial_ref_mercator
        #re-focus using Buffer layer for multipage
        if config.if_multi_page == True:
            buffer_layer = arcpy.mapping.ListLayers(geology_mxd, "Buffer",
                                                    df)[0]
            df.extent = buffer_layer.getSelectedExtent(False)
            df.scale = df.scale * 1.1
        df_as_feature = arcpy.Polygon(
            arcpy.Array([
                df.extent.lowerLeft, df.extent.lowerRight,
                df.extent.upperRight, df.extent.upperLeft
            ]), df.spatialReference)
        del df, geology_mxd

        arcpy.Project_management(
            df_as_feature,
            os.path.join(Kml_Config.viewer_temp, "Extent_geol_WGS84.shp"),
            order_obj.spatial_ref_gcs)
        arcpy.Clip_analysis(
            config.data_lyr_geology,
            os.path.join(Kml_Config.viewer_temp, "Extent_geol_WGS84.shp"),
            geology_clip)
        del df_as_feature

        if int(arcpy.GetCount_management(geology_clip).getOutput(0)) != 0:
            arcpy.AddField_management(geology_clip, "ERISBIID", "TEXT", "", "",
                                      "15", "", "NULLABLE", "NON_REQUIRED", "")
            rows = arcpy.UpdateCursor(geology_clip)
            for row in rows:
                id_final = [
                    id[1] for id in config.geology_ids if row.ERIS_KEY == id[0]
                ]
                if id_final != []:
                    row.ERISBIID = id_final[0]
                    rows.updateRow(row)
            del rows
            keep_field_list = ("ERISBIID", "ORIG_LABEL", "UNIT_NAME",
                               "UNIT_AGE", "ROCKTYPE1", "ROCKTYPE2",
                               "UNITDESC")
            field_info = ""
            field_list = arcpy.ListFields(geology_clip)
            for field in field_list:
                if field.name in keep_field_list:
                    if field.name == 'ERISBIID':
                        field_info = field_info + field.name + " " + "ERISBIID" + " VISIBLE;"
                    elif field.name == 'ORIG_LABEL':
                        field_info = field_info + field.name + " " + "Geologic_Unit" + " VISIBLE;"
                    elif field.name == 'UNIT_NAME':
                        field_info = field_info + field.name + " " + "Name" + " VISIBLE;"
                    elif field.name == 'UNIT_AGE':
                        field_info = field_info + field.name + " " + "Age" + " VISIBLE;"
                    elif field.name == 'ROCKTYPE1':
                        field_info = field_info + field.name + " " + "Primary_Rock_Type" + " VISIBLE;"
                    elif field.name == 'ROCKTYPE2':
                        field_info = field_info + field.name + " " + "Secondary_Rock_Type" + " VISIBLE;"
                    elif field.name == 'UNITDESC':
                        field_info = field_info + field.name + " " + "Unit_Description" + " VISIBLE;"
                    else:
                        pass
                else:
                    field_info = field_info + field.name + " " + field.name + " HIDDEN;"
            arcpy.MakeFeatureLayer_management(geology_clip, 'geologyclip_lyr',
                                              "", "", field_info[:-1])
            arcpy.ApplySymbologyFromLayer_management('geologyclip_lyr',
                                                     config.data_lyr_geology)
            arcpy.LayerToKML_conversion(
                'geologyclip_lyr',
                os.path.join(Kml_Config.viewer_dir_kml, "geology.kmz"))
            arcpy.AddMessage(
                '      -- Create geology kmz map: %s' %
                os.path.join(Kml_Config.viewer_dir_kml, "geology.kmz"))
            arcpy.Delete_management('geologyclip_lyr')
        else:
            # print "no geology data to kml"
            arcpy.MakeFeatureLayer_management(geology_clip, 'geologyclip_lyr')
            arcpy.LayerToKML_conversion(
                'geology_clip_lyr',
                os.path.join(Kml_Config.viewer_dir_kml, "geology_nodata.kmz"))
            arcpy.AddMessage(
                '      -- Create geology kmz map: %s' %
                os.path.join(Kml_Config.viewer_dir_kml, "geology_nodata.kmz"))
            arcpy.Delete_management('geology_clip_lyr')
    else:
        arcpy.AddMessage(
            '  -- Geology report is not generatated therfore the geology kml file cannot be exported.'
        )
Exemple #26
0
import arcpy
arcpy.env.workspace = "C:/Users/Matt Layman/Downloads/activities"
arcpy.env.overwriteOutput = True

list = arcpy.ListFiles()
print list

for f in list:
    arcpy.GPXtoFeatures_conversion(f, f + ".shp")
    print arcpy.GetMessages()

newlist = arcpy.ListFiles("*.shp")
arcpy.Merge_management(newlist, "merge_shp")
arcpy.MakeFeatureLayer_management("merge_shp.shp", "merge_lyr")
arcpy.LayerToKML_conversion("merge_lyr", "activities.kmz")
String = "%Folder%/%provName%"
wireless_Layer = wireless
wireless_symbology_lyr = wireless_Layer
v_String__wireless_kmz = wireless_symbology_lyr
plss_layer = plss
plss_symbology_lyr = plss_layer
v_String__plss_kmz = plss_symbology_lyr

# Process: Make Feature Layer
try:
	arcpy.MakeFeatureLayer_management(midmile, midmile_Layer, "", Folder, "OBJECTID OBJECTID VISIBLE NONE;SHAPE SHAPE VISIBLE NONE;PROVALIAS PROVALIAS VISIBLE NONE;PROVNAME PROVNAME VISIBLE NONE;DBANAME DBANAME VISIBLE NONE;FRN FRN VISIBLE NONE;OWNERSHIP OWNERSHIP VISIBLE NONE;BHCAPACITY BHCAPACITY VISIBLE NONE;BHTYPE BHTYPE VISIBLE NONE;LATITUDE LATITUDE VISIBLE NONE;LONGITUDE LONGITUDE VISIBLE NONE;ELEVFEET ELEVFEET VISIBLE NONE;STATEABBR STATEABBR VISIBLE NONE;CONFIDENCE CONFIDENCE HIDDEN NONE;WHO WHO HIDDEN NONE;WHEN WHEN HIDDEN NONE")
except:
    print "YOU FAIL"
try:
	# Process: Layer To KML
	arcpy.LayerToKML_conversion(midmile_Layer, v_String__midmile_kmz, "0", "false", "DEFAULT", "1024", "96", "CLAMPED_TO_GROUND")
except:
    print "YOU FAIL"
try:
	# Process: Make Feature Layer (2)
	arcpy.MakeFeatureLayer_management(wireless, wireless_Layer, "", Folder, "OBJECTID OBJECTID VISIBLE NONE;Shape Shape VISIBLE NONE;PROVALIAS PROVALIAS VISIBLE NONE;PROVNAME PROVNAME VISIBLE NONE;DBANAME DBANAME VISIBLE NONE;FRN FRN VISIBLE NONE;TRANSTECH TRANSTECH VISIBLE NONE;SPECTRUM SPECTRUM VISIBLE NONE;MAXADDOWN MAXADDOWN VISIBLE NONE;MAXADUP MAXADUP VISIBLE NONE;TYPICDOWN TYPICDOWN VISIBLE NONE;TYPICUP TYPICUP VISIBLE NONE;MAXSUBDOWN MAXSUBDOWN VISIBLE NONE;MAXSUBUP MAXSUBUP VISIBLE NONE;CONFIDENCE CONFIDENCE HIDDEN NONE;PRICE PRICE VISIBLE NONE;STATEABBR STATEABBR VISIBLE NONE;ENDUSERCAT ENDUSERCAT VISIBLE NONE;WHO WHO HIDDEN NONE;WHEN WHEN HIDDEN NONE;Shape_Length Shape_Length HIDDEN NONE;Shape_Area Shape_Area HIDDEN NONE")
except:
    print "YOU FAIL"
try:
	# Process: Apply Symbology From Layer (2)
	arcpy.ApplySymbologyFromLayer_management(wireless_Layer, symbology_lyr)
except:
    print "YOU FAIL"
try:
	# Process: Layer To KML (2)
	arcpy.LayerToKML_conversion(wireless_symbology_lyr, v_String__wireless_kmz, "0", "false", "DEFAULT", "1024", "96", "CLAMPED_TO_GROUND")
Exemple #28
0
def clip_contour_lines(order_obj):
    contour_clip = os.path.join(config.scratch_folder, "contour_clip.shp")
    arcpy.Clip_analysis(config.data_lyr_contour, config.topo_frame,
                        contour_clip)

    if int(arcpy.GetCount_management(contour_clip).getOutput(0)) != 0:
        keep_field_list = ("CONTOURELE")
        field_info = ""
        field_list = arcpy.ListFields(contour_clip)
        for field in field_list:
            if field.name in keep_field_list:
                if field.name == 'CONTOURELE':
                    field_info = field_info + field.name + " " + "elevation" + " VISIBLE;"
                else:
                    pass
            else:
                field_info = field_info + field.name + " " + field.name + " HIDDEN;"
        arcpy.MakeFeatureLayer_management(contour_clip, 'contour_clip_lyr', "",
                                          "", field_info[:-1])
        arcpy.ApplySymbologyFromLayer_management('contour_clip_lyr',
                                                 config.data_lyr_contour)
        arcpy.LayerToKML_conversion(
            'contour_clip_lyr',
            os.path.join(Kml_Config.viewer_dir_relief, "contour_clip.kmz"))
        arcpy.AddMessage(
            '      -- Create contour kmz map: %s' %
            os.path.join(Kml_Config.viewer_dir_relief, "contour_clip.kmz"))
        arcpy.Delete_management('contour_clip_lyr')
    else:
        arcpy.AddMessage('no contour data, no kml to folder')
        arcpy.MakeFeatureLayer_management(contour_clip, 'contour_clip_lyr')
        arcpy.LayerToKML_conversion(
            'contour_clip_lyr',
            os.path.join(Kml_Config.viewer_dir_relief,
                         'contour_clip_nodata.kmz'))
        arcpy.AddMessage('      -- Create contour kmz map: %s' % os.path.join(
            Kml_Config.viewer_dir_relief, 'contour_clip_nodata.kmz'))
        arcpy.Delete_management('contour_clip_lyr')

    if os.path.exists(
            os.path.join(config.viewer_path, order_obj.number + "_psr_kml")):
        shutil.rmtree(
            os.path.join(config.viewer_path, order_obj.number + "_psr_kml"))
    shutil.copytree(
        os.path.join(config.scratch_folder, order_obj.number + "_psr_kml"),
        os.path.join(config.viewer_path, order_obj.number + "_psr_kml"))
    url = config.upload_link + 'PSRKMLUpload?ordernumber=' + order_obj.number
    urllib.urlopen(url)

    if os.path.exists(
            os.path.join(config.viewer_path, order_obj.number + "_psr_topo")):
        shutil.rmtree(
            os.path.join(config.viewer_path, order_obj.number + "_psr_topo"))
    shutil.copytree(
        os.path.join(config.scratch_folder, order_obj.number + "_psr_topo"),
        os.path.join(config.viewer_path, order_obj.number + "_psr_topo"))
    url = config.upload_link + "PSRTOPOUpload?ordernumber=" + order_obj.number
    urllib.urlopen(url)

    if os.path.exists(
            os.path.join(config.viewer_path,
                         order_obj.number + '_psr_relief')):
        shutil.rmtree(
            os.path.join(config.viewer_path, order_obj.number + '_psr_relief'))
    shutil.copytree(
        os.path.join(config.scratch_folder, order_obj.number + '_psr_relief'),
        os.path.join(config.viewer_path, order_obj.number + '_psr_relief'))
    url = config.upload_link + "ReliefUpload?ordernumber=" + order_obj.number
    urllib.urlopen(url)
Exemple #29
0
import arcpy
w = r'C:\\Users\\Winrock\\Documents\\ArcGIS\\Packages\\Untit\\KML'
o = r"D:\Database\CREL_Database\CREL_DATABASE\SRF_Shoronkhola_Range\KMLs\\"
arcpy.env.workspace = w
f = arcpy.ListFiles()
for i in f:
    out = o + i + '.kmz'
    arcpy.LayerToKML_conversion(i, out)
# Calculate characteristics of layers
arcpy.RiverLength_geohms(River)
arcpy.RiverSlope_geohms(DEM, River)
arcpy.BasinSlope_geohms(Slope, Subbasin)
arcpy.LongestFlowpath_geohms(DEM, Fdr, Subbasin, LongestFlowpath)
arcpy.BasinCentroid_geohms("Longest flow path", Subbasin, BasinCentroid, Fac,
                           River, LongestFlowpath)
arcpy.CentroidElevation_geohms(DEM, BasinCentroid)

# !WARNING! there may appear an error in CentroidalLongestFlowpath_geohms tool. More info:  https://geonet.esri.com/thread/171694
arcpy.CentroidalLongestFlowpath_geohms(Subbasin, "BasinCentroid" + puente,
                                       "LongestFlowpath" + puente,
                                       CentroidalLongestFlowpath)

# add CN (curve number) and Ia (initial abstraction) layers
CNgrid = r"path\to\cn\layer"
IAgrid = r"C:\PUNO\recursos\MAPAS CN\ia"
arcpy.MakeRasterLayer_management(CNgrid, "nciii")
arcpy.MakeRasterLayer_management(IAgrid, "ia")

# Set calculation methods
arcpy.SelectHMSProcesses_geohms(Subbasin, River, "SCS", "SCS", "None",
                                "Muskingum")

# Name Rivers and Basins
arcpy.RiverAutoName_geohms(River)
arcpy.BasinAutoName_geohms(Subbasin)

# export basin layer to KML format in order to use it in GoogleEarth
arcpy.LayerToKML_conversion(Subbasin, "subbain.kmz")