ArcGIS Pro 3.1 API Reference Guide
ArcGIS.Desktop.Mapping Namespace / LayerFactory Class / CreateLayer Method / CreateLayer<T>(LayerCreationParams,ILayerContainerEdit) Method
Expected Layer Type
Can be one of LayerCreationParams derived objects.
A map or group layer instance to which the Layer will be added.
Example

In This Topic
    CreateLayer<T>(LayerCreationParams,ILayerContainerEdit) Method
    In This Topic
    Creates a new Layer instance using the specified LayerCreationParams and adds that to a container such as a map or group layer. This method must be called on the MCT. Use QueuedTask.Run.
    Syntax
    Public Overloads Function CreateLayer(Of T As Layer)( _
       ByVal layerParams As LayerCreationParams, _
       ByVal container As ILayerContainerEdit _
    ) As T

    Parameters

    layerParams
    Can be one of LayerCreationParams derived objects.
    container
    A map or group layer instance to which the Layer will be added.

    Type Parameters

    T
    Expected Layer Type

    Return Value

    A specific Layer instance corresponding to type T.
    Exceptions
    ExceptionDescription
    This method or property must be called within the lambda passed to QueuedTask.Run.
    LayerCreationParams or container is null.
    Cannot create the layer of the specified type with the set of LayerCreationParams.
    Example
    Create GraphicsLayer
    var map = MapView.Active.Map;
    if (map.MapType != MapType.Map)
      return;// not 2D
    
    var gl_param = new GraphicsLayerCreationParams { Name = "Graphics Layer" };
    QueuedTask.Run(() =>
    {
      //By default will be added to the top of the TOC
      var graphicsLayer = LayerFactory.Instance.CreateLayer<ArcGIS.Desktop.Mapping.GraphicsLayer>(gl_param, map);
    
      //Add to the bottom of the TOC
      gl_param.MapMemberIndex = -1; //bottom
      LayerFactory.Instance.CreateLayer<ArcGIS.Desktop.Mapping.GraphicsLayer>(gl_param, map);
    
      //Add a graphics layer to a group layer...
      var group_layer = map.GetLayersAsFlattenedList().OfType<GroupLayer>().First();
      LayerFactory.Instance.CreateLayer<ArcGIS.Desktop.Mapping.GraphicsLayer>(gl_param, group_layer);
    
      //TODO...use the graphics layer
      //
    
      // or use the specific CreateGroupLayer method
      LayerFactory.Instance.CreateGroupLayer(map, -1, "Graphics Layer");
    });
    Create layer with create-params
    var flyrCreatnParam = new FeatureLayerCreationParams(new Uri(@"c:\data\world.gdb\cities"))
    {
      Name = "World Cities",
      IsVisible = false,
      MinimumScale = 1000000,
      MaximumScale = 5000,
      // At 2.x - DefinitionFilter = new CIMDefinitionFilter()
      //{
      //  DefinitionExpression = "Population > 100000",
      //  Name = "More than 100k"
      //},
      DefinitionQuery = new DefinitionQuery(whereClause: "Population > 100000", name: "More than 100k"),
      RendererDefinition = new SimpleRendererDefinition()
      {
        SymbolTemplate = SymbolFactory.Instance.ConstructPointSymbol(
          CIMColor.CreateRGBColor(255, 0, 0), 8, SimpleMarkerStyle.Hexagon).MakeSymbolReference()
      }
    };
    
    var featureLayer = LayerFactory.Instance.CreateLayer<FeatureLayer>(
      flyrCreatnParam, map);
    Create FeatureLayer and add to Map using LayerCreationParams
    //Note: Call within QueuedTask.Run()
    var layerDoc = new LayerDocument(@"E:\Data\SDK\Default2DPointSymbols.lyrx");
    var createParams = new LayerCreationParams(layerDoc.GetCIMLayerDocument());
    LayerFactory.Instance.CreateLayer<FeatureLayer>(createParams, MapView.Active.Map);
    Create TopologyLayer with an Uri pointing to a Topology dataset
    var path = @"D:\Data\CommunitySamplesData\Topology\GrandTeton.gdb\BackCountry\Backcountry_Topology";
    var lcp = new TopologyLayerCreationParams(new Uri(path));
    lcp.Name = "GrandTeton_Backcountry";
    lcp.AddAssociatedLayers = true;
    var topoLayer = LayerFactory.Instance.CreateLayer<ArcGIS.Desktop.Mapping.TopologyLayer>(lcp, MapView.Active.Map);
    Create Topology Layer using Topology dataset
    //Note: Call within QueuedTask.Run()
    //Get the Topology of another Topology layer
    var existingTopology = MapView.Active.Map.GetLayersAsFlattenedList().OfType<TopologyLayer>().FirstOrDefault();
    if (existingTopology != null)
    {
      var topology = existingTopology.GetTopology();
      //Configure the settings for a new Catalog layer using the CatalogDataset of an existing layer
      var topologyLyrParams = new TopologyLayerCreationParams(topology);
      topologyLyrParams.Name = "NewTopologyLayerFromAnotherTopologyLayer";
      topologyLyrParams.AddAssociatedLayers = true;
      LayerFactory.Instance.CreateLayer<TopologyLayer>(topologyLyrParams, MapView.Active.Map);
    }
    Create Catalog Layer using Uri to a Catalag Feature Class
    //Note: Call within QueuedTask.Run()
    var createParams = new CatalogLayerCreationParams(new Uri(@"C:\CatalogLayer\CatalogDS.gdb\HurricaneCatalogDS"));
    //Set the definition query
    createParams.DefinitionQuery = new DefinitionQuery("Query1", "cd_itemname = 'PuertoRico'");
    //Set name of the new Catalog Layer
    createParams.Name = "PuertoRico";
    //Create Layer
    var catalogLayer = LayerFactory.Instance.CreateLayer<CatalogLayer>(createParams, MapView.Active.Map);
    Create Catalog Layer using CatalogDataset
    //Note: Call within QueuedTask.Run()
    //Get the CatalogDataset of another Catalog layer
    var existingCatalogLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<CatalogLayer>().FirstOrDefault();
    if (existingCatalogLayer != null)
    {
      var catalogDataset = existingCatalogLayer.GetCatalogDataset();
      //Configure the settings for a new Catalog layer using the CatalogDataset of an existing layer
      var catalogLyrParams = new CatalogLayerCreationParams(catalogDataset);
      catalogLyrParams.Name = "NewCatalogLayerFromAnotherCatalogLayer";
      catalogLyrParams.DefinitionQuery = new DefinitionQuery("Query1", "cd_itemname = 'Asia'");
      LayerFactory.Instance.CreateLayer<CatalogLayer>(catalogLyrParams, MapView.Active.Map);
    }
    Add MapNotes to the active map
    //Gets the collection of layer template packages installed with Pro for use with maps
    var items = MapView.Active.Map.LayerTemplatePackages;
    //Iterate through the collection of items to add each Map Note to the active map
    foreach (var item in items)
    {
      //Create a parameter item for the map note
      var layer_params = new LayerCreationParams(item);
      layer_params.IsVisible = false;
      await QueuedTask.Run(() =>
      {
        //Create a feature layer for the map note
        var layer = LayerFactory.Instance.CreateLayer<Layer>(layer_params, MapView.Active.Map);
      });
    }
    Create a new SubTypeGroupLayer
    var subtypeGroupLayerCreateParam = new SubtypeGroupLayerCreationParams
    (
        new Uri(@"c:\data\SubtypeAndDomain.gdb\Fittings")
    );
    
    // Define Subtype layers
    //At 2.x - var rendererDefn1 = new UniqueValueRendererDefinition(new string[] { "type" });
    var rendererDefn1 = new UniqueValueRendererDefinition(new List<string> { "type" });
    var renderDefn2 = new SimpleRendererDefinition()
    {
      SymbolTemplate = SymbolFactory.Instance.ConstructPointSymbol(
              CIMColor.CreateRGBColor(255, 0, 0), 8, SimpleMarkerStyle.Hexagon).MakeSymbolReference()
    };
    subtypeGroupLayerCreateParam.SubtypeLayers = new List<SubtypeFeatureLayerCreationParams>()
    {
      //define first subtype layer with unique value renderer
      //At 2.x - new SubtypeFeatureLayerCreationParams(new UniqueValueRendererDefinition(new string[] { "type" }), 1),
      new SubtypeFeatureLayerCreationParams(new UniqueValueRendererDefinition(new List<string> { "type" }), 1),
    
      //define second subtype layer with simple symbol renderer
      new SubtypeFeatureLayerCreationParams(renderDefn2, 2)
    };
    
    // Define additional parameters
    //At - 2.x subtypeGroupLayerCreateParam.DefinitionFilter = new CIMDefinitionFilter()
    //{
    //  Name = "IsActive",
    //  DefinitionExpression = "Enabled = 1"
    //};
    subtypeGroupLayerCreateParam.DefinitionQuery = new DefinitionQuery(whereClause: "Enabled = 1", name: "IsActive");
    subtypeGroupLayerCreateParam.IsVisible = true;
    subtypeGroupLayerCreateParam.MinimumScale = 50000;
    
    SubtypeGroupLayer subtypeGroupLayer2 = LayerFactory.Instance.CreateLayer<SubtypeGroupLayer>(
                  subtypeGroupLayerCreateParam, MapView.Active.Map);
    Create layer from a lyrx file
    var lyrDocFromLyrxFile = new LayerDocument(@"d:\data\cities.lyrx");
    var cimLyrDoc = lyrDocFromLyrxFile.GetCIMLayerDocument();
    
    //modifying its renderer symbol to red
    var r = ((CIMFeatureLayer)cimLyrDoc.LayerDefinitions[0]).Renderer as CIMSimpleRenderer;
    r.Symbol.Symbol.SetColor(new CIMRGBColor() { R = 255 });
    
    //optionally save the updates out as a file
    lyrDocFromLyrxFile.Save(@"c:\data\cities_red.lyrx");
    
    //get a json representation of the layer document and you want store away...
    var aJSONString = lyrDocFromLyrxFile.AsJson();
    
    //... and load it back when needed
    lyrDocFromLyrxFile.Load(aJSONString);
    cimLyrDoc = lyrDocFromLyrxFile.GetCIMLayerDocument();
    
    //create a layer and add it to a map
    var lcp = new LayerCreationParams(cimLyrDoc);
    var lyr = LayerFactory.Instance.CreateLayer<FeatureLayer>(lcp, map);
    Add a WMS service
    // Create a connection to the WMS server
    var serverConnection = new CIMInternetServerConnection { URL = "URL of the WMS service" };
    var connection = new CIMWMSServiceConnection { ServerConnection = serverConnection };
    
    // Add a new layer to the map
    var layerParams = new LayerCreationParams(connection);
    await QueuedTask.Run(() =>
    {
      var layer = LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParams, MapView.Active.Map);
    });
    Add a WFS Service
    CIMStandardDataConnection cIMStandardDataConnection = new CIMStandardDataConnection()
    {
      WorkspaceConnectionString = @"SWAPXY=TRUE;SWAPXYFILTER=FALSE;URL=http://sampleserver6.arcgisonline.com/arcgis/services/SampleWorldCities/MapServer/WFSServer;VERSION=2.0.0",
      WorkspaceFactory = WorkspaceFactory.WFS,
      Dataset = "Continent",
      DatasetType = esriDatasetType.esriDTFeatureClass
    };
    
    // Add a new layer to the map
    var layerPamsDC = new LayerCreationParams(cIMStandardDataConnection);
    await QueuedTask.Run(() =>
    {
      Layer layer = LayerFactory.Instance.CreateLayer<FeatureLayer>(layerPamsDC, MapView.Active.Map);
    });
    Create a query layer
    await QueuedTask.Run(() =>
    {
      Map map = MapView.Active.Map;
      Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri(@"C:\Connections\mySDE.sde")));
      CIMSqlQueryDataConnection sqldc = new CIMSqlQueryDataConnection()
      {
        WorkspaceConnectionString = geodatabase.GetConnectionString(),
        GeometryType = esriGeometryType.esriGeometryPolygon,
        OIDFields = "OBJECTID",
        Srid = "102008",
        SqlQuery = "select * from MySDE.dbo.STATES",
        Dataset = "States"
      };
      var lcp = new LayerCreationParams(sqldc)
      {
        Name = "States"
      };
      FeatureLayer flyr = LayerFactory.Instance.CreateLayer<FeatureLayer>(lcp, map);
    });
    Create a New Elevation Surface
    //Note: call within QueuedTask.Run()
    //Define a ServiceConnection to use for the new Elevation surface
    var serverConnection = new CIMInternetServerConnection
    {
      Anonymous = true,
      HideUserProperty = true,
      URL = "https://elevation.arcgis.com/arcgis/services"
    };
    CIMAGSServiceConnection serviceConnection = new CIMAGSServiceConnection
    {
      ObjectName = "WorldElevation/Terrain",
      ObjectType = "ImageServer",
      URL = "https://elevation.arcgis.com/arcgis/services/WorldElevation/Terrain/ImageServer",
      ServerConnection = serverConnection
    };
    //Defines a new elevation source set to the CIMAGSServiceConnection defined above
    //At 2.x - var newElevationSource = new ArcGIS.Core.CIM.CIMElevationSource
    //{
    //  VerticalUnit = ArcGIS.Core.Geometry.LinearUnit.Meters,
    //  DataConnection = serviceConnection,
    //  Name = "WorldElevation/Terrain",
    //  Visibility = true
    //};
    //The elevation surface
    //At 2.x - var newElevationSurface = new ArcGIS.Core.CIM.CIMMapElevationSurface
    //{
    //  Name = "New Elevation Surface",
    //  BaseSources = new ArcGIS.Core.CIM.CIMElevationSource[1] { newElevationSource },
    //  Visibility = true,
    //  ElevationMode = ElevationMode.CustomSurface,
    //  VerticalExaggeration = 1,
    //  EnableSurfaceShading = false,
    //  SurfaceTINShadingMode = SurfaceTINShadingMode.Smooth,
    //  Expanded = false,
    //  MapElevationID = "{3DEC3CC5-7C69-4132-A700-DCD5BDED14D6}"
    //};
    //Get the active map
    var map = MapView.Active.Map;
    //Get the elevation surfaces defined in the map
    //At 2.x - var listOfElevationSurfaces = definition.ElevationSurfaces.ToList();
    var listOfElevationSurfaces = map.GetElevationSurfaceLayers();
    //Add the new elevation surface 
    //At 2.x - listOfElevationSurfaces.Add(newElevationSurface);
    var elevationLyrCreationParams = new ElevationLayerCreationParams(serviceConnection);
    var elevationSurface = LayerFactory.Instance.CreateLayer<ElevationSurfaceLayer>(
           elevationLyrCreationParams, map);
    Add an elevation source to an existing elevation surface layer
    // wrap in QueuendTask.Run
    
    // surfaceLayer could also be the ground layer
    
    string uri = "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer";
    var createParams = new ElevationLayerCreationParams(new Uri(uri));
    createParams.Name = "Terrain 3D";
    var eleSourceLayer = LayerFactory.Instance.CreateLayer<Layer>(createParams, surfaceLayer);
    Create a raster layer with a new colorizer definition
      // Create a new stretch colorizer definition using default constructor.
      StretchColorizerDefinition stretchColorizerDef = new StretchColorizerDefinition();
      var rasterLayerCreationParams = new RasterLayerCreationParams(new Uri(url))
      {
        ColorizerDefinition = stretchColorizerDef,
        Name = layerName,
        MapMemberIndex = 0
      };
      await QueuedTask.Run(() =>
      {
        // Create a raster layer using the colorizer definition created above.
        // Note: You can create a raster layer from a url, project item, or data connection.
        RasterLayer rasterLayerfromURL =
    LayerFactory.Instance.CreateLayer<RasterLayer>(rasterLayerCreationParams, aMap);
      });
    Create a mosaic layer with a new colorizer definition
      // Create a new colorizer definition using default constructor.
      StretchColorizerDefinition stretchColorizerDef = new StretchColorizerDefinition();
      var rasterLayerCreationParams = new RasterLayerCreationParams(new Uri(url))
      {
        Name = layerName,
        ColorizerDefinition = stretchColorizerDef,
        MapMemberIndex = 0
    
      };
      await QueuedTask.Run(() =>
      {
        // Create a mosaic layer using the colorizer definition created above.
        // Note: You can create a mosaic layer from a url, project item, or data connection.
        MosaicLayer newMosaicLayer =
    LayerFactory.Instance.CreateLayer<MosaicLayer>(rasterLayerCreationParams, aMap);
      });
    Create an image service layer with a new colorizer definition
      // Create a new colorizer definition using default constructor.
      StretchColorizerDefinition stretchColorizerDef = new StretchColorizerDefinition();
      var rasterLayerCreationParams = new RasterLayerCreationParams(new Uri(url))
      {
        Name = layerName,
        ColorizerDefinition = stretchColorizerDef,
        MapMemberIndex = 0
      };
      await QueuedTask.Run(() =>
      {
        // Create an image service layer using the colorizer definition created above.
        ImageServiceLayer imageServiceLayer =
    LayerFactory.Instance.CreateLayer<ImageServiceLayer>(rasterLayerCreationParams, aMap);
      });
    Create a Scene Layer
    var sceneLayerUrl = @"https://myportal.com/server/rest/services/Hosted/SceneLayerServiceName/SceneServer";
    //portal items also ok as long as the portal is the current active portal...
    //var sceneLayerUrl = @"https://myportal.com/home/item.html?id=123456789abcdef1234567890abcdef0";
    
    await QueuedTask.Run(() =>
    {
      //Create with initial visibility set to false. Add to current scene
      var createparams = new LayerCreationParams(new Uri(sceneLayerUrl, UriKind.Absolute))
      {
        IsVisible = false
      };
    
      //cast to specific type of scene layer being created - in this case FeatureSceneLayer
      var sceneLayer = LayerFactory.Instance.CreateLayer<Layer>(
               createparams, MapView.Active.Map) as FeatureSceneLayer;
      //or...specify the cast directly
      var sceneLayer2 = LayerFactory.Instance.CreateLayer<FeatureSceneLayer>(
               createparams, MapView.Active.Map);
      //ditto for BuildingSceneLayer, PointCloudSceneLayer, IntegratedMeshSceneLayer
      //...
    });
          
    EsriHttpClient: Get a Service Layer and Add it to Pro
    UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
    {
      Path = "sharing/rest/search"
    };
    string layers = "(type:\"Map Service\" OR type:\"Image Service\" OR type:\"Feature Service\" OR type:\"WMS\" OR type:\"KML\")";
    //any public layer content
    searchURL.Query = string.Format("q={0}&f=json", layers);
    
    EsriHttpClient httpClient = new EsriHttpClient();
    
    var searchResponse = httpClient.Get(searchURL.Uri.ToString());
    dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());
    
    long numberOfTotalItems = resultItems.total.Value;
    if (numberOfTotalItems == 0)
      return;
    
    List<dynamic> resultItemList = new List<dynamic>();
    resultItemList.AddRange(resultItems.results);
    //get the first result
    dynamic item = resultItemList[0];
    
    string itemID = item.id;
    Item currentItem = ItemFactory.Instance.Create(itemID, ItemFactory.ItemType.PortalItem);
    
    await QueuedTask.Run(() =>
    {
          //Create a LayerCreationParam
          var layerParam = new LayerCreationParams(currentItem);
          // if we have an item that can be turned into a layer
          // add it to the map
          if (LayerFactory.Instance.CanCreateLayerFrom(currentItem))
        LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParam, MapView.Active.Map);
    });
    
    Requirements

    Target Platforms: Windows 11, Windows 10

    ArcGIS Pro version: 3.0 or higher.
    See Also