KML To Layer (Conversion)

Summary

Converts a .kml or .kmz file into datasets in a geodatabase and a layer file. The layer file maintains the symbology of the input .kml or .kmz file.

Learn more about KML support in ArcGIS

Usage

  • The output datasets will be named Points, Lines, Polygons, or Multipatches, depending on the feature types in the input file.

    Each feature class created will have attributes that contain information about the input file. The original folder structure, name, and pop-up information, as well as fields that help define how the features sit on a surface, compose the attributes of each feature.

  • The output layer file maintaining the original KML symbology will be created in the target folder.

  • Rasters, or ground overlays, will be converted to a mosaic dataset in the output geodatabase. The source raster in its native format will be copied to a GroundOverlays folder in the target folder. Ground overlays are not converted by default. Use the Include ground overlay parameter to create rasters.

    License:

    Use of the Include ground overlay parameter to create a mosaic dataset requires a Desktop Standard license.

    Note:

    Converting overlays using this tool may take a long time, depending on the source data. All available rasters and overlays in the KML will be converted. All of the imagery will be converted if a KML references a service that provides imagery. Highly detailed imagery may also take a long time to convert due to its file size.

  • Output datasets will be in the WGS84 coordinate system. Feature classes can be reprojected to another coordinate system using the Project tool.

  • Input up to KMZ version 2.2 of the OGC KML standard is mostly supported. Point locations that use the address tag (by way of geocoding) are not supported. A valid latitude and longitude location is required in the source KML.

  • ArcGIS AllSource supports adding KML and KMZ layers to the map in their original format without conversion. However, to perform editing or to modify the layers in any way, the layer must be converted using this tool. You can select the KML layer as the input to this tool.

Parameters

LabelExplanationData Type
Input File (KML or KMZ)

The .kml or .kmz file that will be converted to geodatabase datasets.

File; KML Layer
Target Folder

The destination folder where the output geodatabase and layer file (.lyrx) will be created.

Folder
Output Name
(Optional)

A name that will be used for both the output geodatabase and layer file (.lyrx). The default is the name of the input file.

You can specify the name of an existing geodatabase in the target folder, and the conversion will write new datasets into the existing geodatabase. If the geodatabase with the specified name does not exist, it will be created in the target folder.

String
Include ground overlay
(Optional)

Specifies whether ground overlays from the KML will be included in the output.

Use caution if the KMZ points to a service that serves imagery. The tool will attempt to convert the raster imagery at all available scales. This process may be lengthy and possibly overwhelm the server or time out.

  • Checked—Ground overlays will be included in the output.
  • Unchecked—Ground overlays will not be included in the output. This is the default.
Boolean
Output Suffix
(Optional)

A suffix that will be added to the names of all output feature datasets, feature classes, mosaic datasets, and layer files. If no suffix is specified, the name of the feature dataset in the output geodatabase will be Placemarks.

String

Derived Output

LabelExplanationData Type
Output Layer File

The output layer file.

Group Layer
Output Geodatabase

The output geodatabase containing feature classes in a feature dataset, and a mosaic dataset if ground overlays were included.

Workspace

arcpy.conversion.KMLToLayer(in_kml_file, output_folder, {output_data}, {include_groundoverlay}, {out_suffix})
NameExplanationData Type
in_kml_file

The .kml or .kmz file that will be converted to geodatabase datasets.

File; KML Layer
output_folder

The destination folder where the output geodatabase and layer file (.lyrx) will be created.

Folder
output_data
(Optional)

A name that will be used for both the output geodatabase and layer file (.lyrx). The default is the name of the input file.

You can specify the name of an existing geodatabase in the target folder, and the conversion will write new datasets into the existing geodatabase. If the geodatabase with the specified name does not exist, it will be created in the target folder.

String
include_groundoverlay
(Optional)

Specifies whether ground overlays from the KML will be included in the output.

Use caution if the KMZ points to a service that serves imagery. The tool will attempt to convert the raster imagery at all available scales. This process may be lengthy and possibly overwhelm the server or time out.

  • GROUNDOVERLAYGround overlays will be included in the output.
  • NO_GROUNDOVERLAYGround overlays will not be included in the output. This is the default.
Boolean
out_suffix
(Optional)

A suffix that will be added to the names of all output feature datasets, feature classes, mosaic datasets, and layer files. If no suffix is specified, the name of the feature dataset in the output geodatabase will be Placemarks.

String

Derived Output

NameExplanationData Type
output_layer

The output layer file.

Group Layer
out_geodatabase

The output geodatabase containing feature classes in a feature dataset, and a mosaic dataset if ground overlays were included.

Workspace

Code sample

KMLToLayer example 1 (Python window)

Convert a .kmz file to a file geodatabase from the Python window.

import arcpy

arcpy.KMLToLayer_conversion(r'C:\kmls\earthquakes.kml',r'C:\gisdata\fromkmls','earthquake_09')
KMLToLayer example 2 (stand-alone script)

The following script converts a folder of .kmz and .kml files to their respective file geodatabase. The feature classes in the file geodatabases are then consolidated into a single file geodatabase.

Note:
This script does not maintain the layer files from the KMLToLayer function.

# Name: BatchKML_to_GDB.py
# Description: Convert a directory of KMLs and copy the output to a single 
#              fGDB. A 2-step process: first convert the KML files; then 
#              copy the feature classes.

# Import system modules
import arcpy
import os

# Set workspace (where all the KMLs are)
arcpy.env.workspace = "C:/VancouverData/KML"

# Set local variables and location for the consolidated file geodatabase
out_location = "C:/WorkingData/fGDBs"
gdb = 'AllKMLLayers.gdb'
gdb_location = os.path.join(out_location, gdb)

# Create the primary file geodatabase
arcpy.management.CreateFileGDB(out_location, gdb)

# Convert all KMZ and KML files found in the current workspace
for kmz in arcpy.ListFiles('*.KM*'):
    print("CONVERTING: {0}".format(os.path.join(arcpy.env.workspace, kmz)))
    arcpy.conversion.KMLToLayer((os.path.join(arcpy.env.workspace, kmz), out_location)

# Change the workspace to fGDB location
arcpy.env.workspace = out_location

# Loop through all the file geodatabases in the workspace
wks = arcpy.ListWorkspaces('*', 'FileGDB')
# Skip the primary GDB
wks.remove(gdb_location)

for fgdb in wks:
    # Change the workspace to the current file geodatabase
    arcpy.env.workspace = fgdb

    # For every feature class inside, copy it to the primary and use the name 
    # from the original fGDB  
    feature_classes = arcpy.ListFeatureClasses('*', '', 'Placemarks')
    for fc in feature_classes:
        print("COPYING: {} FROM: {}".format(fc, fgdb))
        fcCopy = os.path.join(fgdb, 'Placemarks', fc)
        arcpy.conversion.FeatureClassToFeatureClass(
            fcCopy, gdb_location, fgdb[fgdb.rfind(os.sep) + 1:-4])
KMLToLayer example 3 (stand-alone script)

The following script converts a .kmz file and extracts the HTML pop-up data to field attributes.

Note:
This script does not maintain the layer files from the KMLToLayer function.

# Name: Extract_KML_popup_table.py
# Description: Convert a .kmz file and transfer a 2-column table from the pop-up 
#              to the field attributes.

# Import system modules
import arcpy
import os

# Set local variables and location for the consolidated file geodatabase
out_location = "C:/WorkingData/fGDBs"
gdb = 'SCP BoardDistricts.gdb'
gdb_location = os.path.join(out_location, gdb)

# Set kmz path
kmz = os.path.join(out_location, "SCP BoardDistricts.kmz")

# Convert all KMZ files to feature in the current workspace
arcpy.conversion.KMLToLayer(kmz, out_location)
    
# Change the workspace to fGDB location
arcpy.env.workspace = gdb_location

# Loop through all the file geodatabases in the workspace
feature_classes = arcpy.ListFeatureClasses('*', '', 'Placemarks')
for fc in feature_classes:
    popup_info_field_name = 'PopupInfo'
    field_names = [['gs_guid', 'TEXT', '#', 255, None, ''], 
                   ['gs_vc_revision', 'TEXT', '#', 255, None, ''], 
                   ['gs_vc_modified_sw', 'TEXT', '#', 255, None, ''], 
                   ['gs_old_objectid', 'TEXT', '#', 255, None, ''], 
                   ['gs_date_created', 'TEXT', '#', 255, None, ''], 
                   ['gs_date_modified', 'TEXT', '#', 255, None, ''], 
                   ['gs_code', 'TEXT', '#', 255, None, ''], 
                   ['gs_reference_scale', 'TEXT', '#', 255, None, ''], 
                   ['gs_description', 'TEXT', '#', 255, None, ''], 
                   ['gs_plot_scale', 'TEXT', '#', 255, None, ''], 
                   ['gs_nisc_guid', 'TEXT', '#', 255, None, ''], 
                   ['gs_mapped_by', 'TEXT', '#', 255, None, ''], 
                   ['gs_district', 'TEXT', 'Name', 255, None, ''], 
                   ['gs_boardmember', 'TEXT', '#', 255, None, ''], 
                   ['gs_servicetype', 'TEXT', 'Name', 255, None, ''], 
                   ['gs_legacy_futuraguid', 'TEXT', '#', 255, None, ''], 
                   ['gs_last_modified_by', 'TEXT', '#', 255, None, ''], 
                   ['gs_shape_from_gps_sw', 'TEXT', '#', 255, None, ''], 
                   ['gs_district_code', 'TEXT', '#', 255, None, ''], 
                   ['gs_district_name', 'TEXT', '#', 255, None, '']]
    arcpy.management.AddFields(fc, field_names, None)
    field_calculation = [[calc[0], f"extract_field(!{popup_info_field_name}!, '{calc[0]}')"] for calc in field_names]
    arcpy.management.CalculateFields(
        fc, "PYTHON3", field_calculation, 
"""from lxml import etree as _etree
def extract_field(s, field):
    ''' Extract fields from pop-up from each record in the calculate fields tool '''
    html = _etree.HTML(s)

    # Get all 'td'
    rows = html.xpath('//table/tr/td')
    next_value = False
    for row in rows:
        c = row.text
        if next_value:
            return c
        if c == field:
            next_value = True
    return None""", 
        "NO_ENFORCE_DOMAINS")

Related topics