[GIS] How to use arcpy.mapping to batch export layer to KML

arcpykmllayers

I am trying to export map layers from an MXD to KML using arcpy with the following code:

import arcpy, os, sys, traceback

arcpy.env.overwriteOutput = True

mxd = arcpy.mapping.MapDocument(r"C:\Layer_KML\MXD\Test.mxd")

try:
    for lyr in arcpy.mapping.ListLayers(mxd):
        i = 1 # forgive the wonky naming convention, I just wanted something quick for test purposes
        outKML = "C:\\Layer_KML\\KML\\" + "Test" + str(i) + ".kmz"

        # These lines are where the error/s is occuring
        newLayer = arcpy.SaveToLayerFile_management(lyr, "C:\\Layer_KML\\Layers\\" + str(lyr) + ".lyr")        
        arcpy.LayerToKML_conversion(newLayer, outKML, "20000", "false", "DEFAULT", "1024",     "96")

        i = i + 1

except:
        ...

Though my traceback keeps telling me : {ERROR 000623: Invalid value type for parameter in_layer.} for both (I commented out each indivudally to test) the .SaveToLayerFile, and LayerToKML routines. I am assuming these routines want to except a full file path, while the arcpy.ListLayer() only yields a basename. Maybe? I am really not sure. Any thoughts as to why this isn't working?

I have already seen this question : How to batch export layers to kml in Arcmap and this is not what I am looking for. I want to do this in Python rather than through a toolbox tool.

Any help is appreciated. Thanks!

Best Answer

You don't need to save to layer file, just do this:

import arcpy, os, sys, traceback

arcpy.env.overwriteOutput = True

mxd = arcpy.mapping.MapDocument(r"C:\Layer_KML\MXD\Test.mxd")

try:
    for i, lyr in enumerate(arcpy.mapping.ListLayers(mxd)):
        outKML = "C:\\Layer_KML\\KML\\" + "Test" + str(i + 1) + ".kmz"

        # These lines are where the error/s is occuring
        arcpy.LayerToKML_conversion(lyr, outKML, 20000, "false", "DEFAULT", "1024",     "96")
except:
        ...