KML To Layer (Conversion)

Summary

Converts a .kml or .kmz file into feature classes 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

  • This tool creates a file geodatabase containing a feature class in a feature dataset. The feature class name will be named point, line, polygon, or multipatches, depending on the original features of the input file. At the same folder level as the file geodatabase will be a layer file that can be added to a map to draw the features. This layer file draws features based on their schema of point, line, or polygon, while maintaining the original KML symbology.

    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, all make up the attributes of each feature.

  • Rasters, or ground overlays, will be converted to a mosaic dataset in the file geodatabase. The source raster in its native format is in the GroundOverlays folder at the same level as the output file geodatabase. 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 the KML To Layer 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 take a long time to convert due its file size.

  • Output will be generated in the WGS84 coordinate system. The output features 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.

  • The AllSource 1.3 release introduced native support for KML and KMZ as data sources. To perform geoprocessing operations on a KML layer, it must be converted to features in a file geodatabase. Using the KML to Layer tool, select the KML layer from the Contents menu and drag it into the Input KML File parameter of the tool. After it has been converted, perform the geoprocessing operation on the new output.

Parameters

LabelExplanationData Type
Input KML File

The .kml or .kmz file that will be converted.

File; KML Layer
Output Location

The destination folder for the file geodatabase and layer file (.lyrx).

Folder
Output Data Name
(Optional)

The name of the output file geodatabase and layer file. The default is the name of the input file.

String
Include Ground Overlay
(Optional)

Specifies whether ground overlays from the KML (raster, air photos, and so on) will be included in the output.

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

  • Checked—Ground overlay will be included in the output.
  • Unchecked—Ground overlays will not be included in the output. This is the default.
Boolean

Derived Output

LabelExplanationData Type
Output Layer File

The output layer file.

Group Layer
Output File Geodatabase

The output geodatabase containing a feature class in a feature dataset.

Workspace

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

The .kml or .kmz file that will be converted.

File; KML Layer
output_folder

The destination folder for the file geodatabase and layer file (.lyrx).

Folder
output_data
(Optional)

The name of the output file geodatabase and layer file. The default is the name of the input file.

String
include_groundoverlay
(Optional)

Specifies whether ground overlays (raster, air photos, and so on) will be used.

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

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

Derived Output

NameExplanationData Type
output_layer

The output layer file.

Group Layer
out_geodatabase

The output geodatabase containing a feature class in a feature dataset.

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 into their respective file geodatabase. The feature classes in these 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 copies the output into 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(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 within the calculate field 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")