Ejemplo n.º 1
0
    def onClick(self):
        #save the mxd in some kind of scratch space
        mxd = arcpy.mapping.MapDocument("CURRENT")

        exportMXDPath = r"C:\scratch\kmlConverter.mxd"
        kmlPath = r"C:\scratch\currentLayers.kmz"

        #if these files exist then delete them
        if os.path.isfile(exportMXDPath):
            os.remove(exportMXDPath)
        if os.path.isfile(kmlPath):
            os.remove(kmlPath)

        mxd.saveACopy(exportMXDPath)

        del mxd  #delete the current mxd object to prevent schma locks

        mxdCopy = arcpy.mapping.MapDocument(exportMXDPath)

        #get the extent of the current map
        df = arcpy.mapping.ListDataFrames(mxdCopy)[0]
        print "the name of the dataframe is: " + df.name
        print "the export path is: " + exportMXDPath

        clippingExtent = df.extent

        #run the map to kml tool with the current extent as the extent parameter
        #MapToKML_conversion (in_map_document, data_frame, out_kmz_file, {map_output_scale}, {is_composite}, {is_vector_to_raster}, {extent_to_export}, {image_size}, {dpi_of_client}, {ignore_zvalue})
        #arcpy.MapToKML_conversion(exportMXDPath, df.name, kmlPath, extent_to_export=clippingExtent)
        arcpy.MapToKML_conversion(exportMXDPath,
                                  df.name,
                                  kmlPath,
                                  extent_to_export=clippingExtent)

        print "deleting lose end objects"

        #delete the copy mxd object to prevent crashing issues
        del mxdCopy
        del df
        del clippingExtent

        print "starting to open kmz file"

        #open the kml file and end the script
        startfile(kmlPath)

        #can help with the error
        #http://www.fhhyc.com/code-to-open-web-browser-crashes-arcmap-when-run-from-a-python-add-in/
Ejemplo n.º 2
0
def makeKML():
    arcpy.AddMessage('Converting to KML...')
    shutil.copy(tempMXD,outputLocation + os.sep + siteName + ".mxd")
    
    resultMXD = arcpy.mapping.MapDocument(outputLocation + os.sep + siteName + ".mxd")
    arcpy.AddMessage('- Template MXD created.')

    layers = arcpy.mapping.ListLayers(resultMXD)
    layers[0].replaceDataSource(outputLocation + os.sep + siteName + ".gdb","FILEGDB_WORKSPACE","parent_sites_"+siteName)
    layers[1].replaceDataSource(outputLocation + os.sep + siteName + ".gdb","FILEGDB_WORKSPACE","hubs_"+siteName)
    layers[2].replaceDataSource(outputLocation + os.sep + siteName + ".gdb","FILEGDB_WORKSPACE","routes_"+siteName)
    resultMXD.save()
    arcpy.AddMessage('- Data Sources reconnected.')

    layers = ""
    resultMXD = ""

    arcpy.MapToKML_conversion(outputLocation + os.sep + siteName + ".mxd", "Layers" ,outputLocation + os.sep + siteName + ".kmz")
    arcpy.AddMessage('- KMZ file created.')
Ejemplo n.º 3
0
    #        os.mkdir(dirName)
    #else:
    #        os.mkdir(dirName)
    # change definition query
    mxd = arcpy.mapping.MapDocument(workspace)
    df = arcpy.mapping.ListDataFrames(mxd)[0]
    co_extent = arcpy.mapping.ListLayers(mxd)[0]
    co_extent.definitionQuery = "sac = '{}'".format(sac)
    # update map view
    Extent = co_extent.getExtent(True)
    df.extent = Extent
    arcpy.RefreshActiveView()
    mxd.saveACopy(kmzDir + "/Study Areas/study_areas_current.mxd", "10.3")
    #arcpy.MapToKML_conversion(mxd, "Layers", filename, "0", "NO_COMPOSITE", "VECTOR_TO_IMAGE", "DEFAULT", "1024", "96", "CLAMPED_TO_GROUND")
    arcpy.MapToKML_conversion(
        in_map_document=kmzDir + "/Study Areas/study_areas_current.mxd",
        data_frame="Layers",
        out_kmz_file="C:/KMZ/DIR/Study Areas/Companies/" + filename + ".kmz",
        map_output_scale="0",
        is_composite="NO_COMPOSITE",
        is_vector_to_raster="VECTOR_TO_IMAGE",
        extent_to_export="DEFAULT",
        image_size="1024",
        dpi_of_client="96",
        ignore_zvalue="CLAMPED_TO_GROUND")
    os.remove(kmzDir + "/Study Areas/study_areas_current.mxd")

print('Done.')
print('\nStart time: {}'.format(start_time))
print('End time: {}'.format(date_and_time()))
Ejemplo n.º 4
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
Ejemplo n.º 5
0
    os.remove(mxdOut)

if os.path.exists(kmzOut2):
    os.remove(kmzOut2)

print 'Saving new mxd'

#mxd.saveACopy(r"C:\Project\Project2.mxd")
mxd.saveACopy(mxdOut)
print '  '
print datetime.datetime.now(), ' ---- CREATING KMZ FILE ---- '
print '  '
print 'Parameters: ', mxdOut, " ", df.name, " ", kmzOut2, " 1"
print 'Wait ....!'
#Export to kml
arcpy.MapToKML_conversion(mxdOut, df.name, kmzOut2, "1")

print datetime.datetime.now(), ' - Kml done!'
#>>n = datetime.datetime.now()
#time.sleep(30)
#print 'Done'
del mxd, df, targetGroupLayer

# zip_susser_v2.py
print '  '
print datetime.datetime.now(), ' ---- VALIDATING KMZ FILE ---- '
print '  '

grimoire = [
    ("FileHeader", "PK\003\004"),
    ("DataDescriptor", "PK\x07\x08"),
Ejemplo n.º 6
0
    #arcpy.MakeFeatureLayer_management("myFC", "My Layer Name")

    inlyr = inloc + os.sep + str(z)
    addLayer = arcpy.mapping.Layer(inlyr)
    print str(inlyr)
    arcpy.mapping.AddLayer(df, addLayer, "TOP")
    count = count + 1
    print count
mxd.save()

sourceLayer = "G:\\Species\\GIS\\WebApp\\FishNet500000\\FishnetLyr_500000\\100_DiazAA.lyr"
layerSymb = arcpy.mapping.Layer(sourceLayer)

count = count - 1
#while count < 1363:
while count\
        >=0:
    updateLayer = arcpy.mapping.ListLayers(mxd)[count]
    arcpy.mapping.UpdateLayer(df, updateLayer, layerSymb, "TRUE")
    print count
    count = count - 1

arcpy.RefreshTOC()
mxd.save()
del mxd

composite = 'NO_COMPOSITE'
dataFrame = 'Layers'
outKML = outlocation + os.sep + kmlname
arcpy.MapToKML_conversion(location, dataFrame, outKML, "1", composite)
Ejemplo n.º 7
0
arcpy.env.workspace = (INPUT_PATH)

print(
    "Processing...\n--------------------------------------------------------")

if len(arcpy.ListFiles('*.mxd')) > 0:
    for mxd in arcpy.ListFiles('*.mxd'):
        dataFrame = 'Layers'
        composite = 'NO_COMPOSITE'
        vector = 'VECTOR_TO_VECTOR'
        pixels = 2048
        dpi = 96
        clamped = 'ABSOLUTE'
        for scale in range(10000, 30001, 10000):
            outKML = mxd[:-4] + '.kmz'
            arcpy.MapToKML_conversion(mxd, dataFrame, outKML, scale, composite,
                                      vector, '', pixels, dpi, clamped)

else:
    arcpy.AddMessage(
        'There are no map documents (*.mxd) in {}'.format(INPUT_PATH))

# for dist in distance_list:
#     output_fc = '{}_Buffer_{}_meters'.format(input_fc, dist)
#     arcpy.Buffer_analysis(input_fc, output_fc, '{} meters'.format(dist))
#     print('PROCESSED: {}_Buffer_{}_meters'.format(input_fc, dist))

END_TIMER = (time.time() - START_TIMER)
print("--------------------------------------------------------")
print("Process completed in {} seconds.".format(round(END_TIMER, 2)))
Ejemplo n.º 8
0
        # print("Processing " + st_county)

        if os.path.isdir(mainDirPath):
                #if os.path.isdir(dirName):
                #        os.rmdir(dirName)
                #        os.mkdir(dirName)
                #else:
                #        os.mkdir(dirName)
        # change definition query
        mxd = arcpy.mapping.MapDocument(workspace)
        df = arcpy.mapping.ListDataFrames(mxd)[0]
        cb_layer = arcpy.mapping.ListLayers(mxd)[2]
        cb_layer.definitionQuery = "fips = '{}'".format(fips)
        cbg_layer = arcpy.mapping.ListLayers(mxd)[1]
        cbg_layer.definitionQuery = "fips = '{}'".format(fips)
        ct_layer = arcpy.mapping.ListLayers(mxd)[0]
        ct_layer.definitionQuery = "fips = '{}'".format(fips)
        # update map view
        Extent = cbg_layer.getExtent(True)
        df.extent = Extent
        arcpy.RefreshActiveView()
        mxd.saveACopy(kmzDir + "/blocksCurrent.mxd", "10.3")
        filename = dirName + "/" + st_county + ".kmz"
        #arcpy.MapToKML_conversion(mxd, "Layers", filename, "0", "NO_COMPOSITE", "VECTOR_TO_IMAGE", "DEFAULT", "1024", "96", "CLAMPED_TO_GROUND")
        arcpy.MapToKML_conversion(in_map_document=kmzDir+"/blocksCurrent.mxd", data_frame="Layers", out_kmz_file= kmzDir + st_full + "/" + st + "_" + county + ".kmz", map_output_scale="0", is_composite="NO_COMPOSITE", is_vector_to_raster="VECTOR_TO_IMAGE", extent_to_export="DEFAULT", image_size="1024", dpi_of_client="96", ignore_zvalue="CLAMPED_TO_GROUND")
        os.remove(kmzDir+"/blocksCurrent.mxd")

print('Done.')
print('\nStart time: {}'.format(start_time))
print('End time: {}'.format(date_and_time()))
Ejemplo n.º 9
0
import arcpy
#import os

print "start script"

location = r"G:\\Species\\GIS\\WebApp\\Mxd\\Diaz_AA_fishnet100000.mxd"
outlocation = r"G:\\Species\\GIS\\WebApp\\KMLs"
kmlname = "Diaz_AA_100000_fishnet.kmz"

print "start"

composite = 'NO_COMPOSITE'
#composite = 'COMPOSITE'
dataFrame = 'Layers'
vector = 'VECTOR_TO_VECTOR'
pixels = 2048
dpi = 96
clamped = 'CLAMPED_TO_GROUND'
#outKML = outlocation+os.sep+kmlname
#arcpy.MapToKML_conversion(location, dataFrame, outKML, "1",composite)

#arcpy.MapToKML_conversion(location, dataFrame, outKML, '',composite, '', '', pixels, dpi, clamped)
arcpy.MapToKML_conversion(
    location, dataFrame,
    r"G:\\Species\\GIS\\WebApp\\KMLs\\Diaz_AA_100000_fishnet.kmz", '',
    composite, '', '', pixels, dpi, clamped)
#arcpy.MapToKML_conversion(location, dataFrame, "Z:\\Species\\GIS\\WebApp\\KMLs\\Diaz_AA_final4.kmz")