test1
layer=arcpy.mapping.Layer( folder+"\\"+"result.shp") mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd)[0] arcpy.mapping.AddLayer(df,layer,"TOP")
test2
layer_name = "acute angle_lyr" arcpy.MakeFeatureLayer_management(out_fc, layer_name,workspace=out_folder) out_layer = "{}\\acute angle_lyr.lyr".format(out_folder) arcpy.SaveToLayerFile_management(layer_name,out_layer) layer=arcpy.mapping.Layer(out_layer) mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd)[0] arcpy.mapping.AddLayer(df,layer,"TOP")
test3
def AddLayerToMap(in_fc, lyr_name,lyrFile_saveFolder): arcpy.MakeFeatureLayer_management(in_fc, lyr_name,workspace=lyrFile_saveFolder) out_layer = "{0}\\{1}.lyr".format(lyrFile_saveFolder,lyr_name) arcpy.SaveToLayerFile_management(lyr_name,out_layer) layer=arcpy.mapping.Layer(out_layer) mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd)[0] arcpy.mapping.AddLayer(df,layer,"TOP") del layer,mxd
终: #in_fc: feature class #lyr_name #lyrFile_saveFolder: a folder used to save layer file. def AddLayerToMap(in_fc, lyr_name,lyrFile_saveFolder): mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd)[0] for lyr in arcpy.mapping.ListLayers(mxd,"*",df): if lyr.name==lyr_name: arcpy.mapping.RemoveLayer(df,lyr) try: arcpy.MakeFeatureLayer_management(in_fc, lyr_name,workspace=lyrFile_saveFolder) # except: # lyr_name=lyr_name+"_"+str(uuid.uuid1()) # arcpy.MakeFeatureLayer_management(in_fc, lyr_name,workspace=lyrFile_saveFolder) out_layer = "{0}\\{1}.lyr".format(lyrFile_saveFolder,lyr_name) if os.path.exists(out_layer): os.remove(out_layer) arcpy.SaveToLayerFile_management(lyr_name,out_layer) arcpy.Delete_management(lyr_name) layer=arcpy.mapping.Layer(out_layer) arcpy.mapping.AddLayer(df,layer,"TOP")