How to add a WMS layer to the map


This tip demonstrates how to add a WMS layer to ArcMap programatically. Although this sample code is intended to work with ArcMap it can also be used with ArcGIS Engine.

How to use

  1. Copy the subroutine to the VBA Editor of an opened map document.
  2. Execute the subroutine.
[VBA]
Private Sub AddWMSLayer()
    
    '' Create an WMSMapLayer Instance - this will be added to the map later
    Dim wmsMapLayer As IWMSGroupLayer
    Set wmsMapLayer = New wmsMapLayer
    
    '' create and configure wms connection name
    '' this is used to store the connection properties
    Dim connName As IWMSConnectionName
    Set connName = New WMSConnectionName
    
    Dim propSet As IPropertySet
    Set propSet = New PropertySet
    propSet.SetProperty "URL", "http://www.geographynetwork.com/ogc/com.esri.ogc.wms.WMSServlet?ServiceName=ESRI_Pop&"
    
    connName.ConnectionProperties = propSet
    
    '' uses the name information to connect to the service
    Dim dataLayer As IDataLayer
    Set dataLayer = wmsMapLayer
    dataLayer.Connect connName
    
    '' get service description out of the layer
    '' the service description contains inforamtion about the wms categories
    '' and layers supported by the service
    Dim serviceDesc As IWMSServiceDescription
    Set serviceDesc = wmsMapLayer.WMSServiceDescription
    
    '' for each wms layer either add the stand-alone layer or
    '' group layer to the WMSMapLayer which will be added to ArcMap
    Dim i As Long
    For i = 0 To serviceDesc.LayerDescriptionCount - 1
        
        Dim layerDesc As IWMSLayerDescription
        Set layerDesc = serviceDesc.LayerDescription(i)
        
        Dim newLayer As ILayer
        
        If (layerDesc.LayerDescriptionCount = 0) Then
            Dim newWMSLayer As IWMSLayer
            Set newWMSLayer = wmsMapLayer.CreateWMSLayer(layerDesc)
            Set newLayer = newWMSLayer
        Else
            Dim grpLayer As IWMSGroupLayer
            Set grpLayer = wmsMapLayer.CreateWMSGroupLayers(layerDesc)
            Set newLayer = grpLayer
        End If
        wmsMapLayer.InsertLayer newLayer, 0
    Next
    
    '' Configure the layer before adding it to the map
    Dim layer As ILayer
    Set layer = wmsMapLayer
    layer.Name = serviceDesc.WMSTitle
    
    '' add layer to Map
    Dim mxDoc As IMxDocument
    Set mxDoc = Document
    mxDoc.FocusMap.AddLayer wmsMapLayer
    
    'refresh
    Dim activeView As IActiveView
    Set activeView = mxDoc.FocusMap
    activeView.Refresh
    
End Sub