How to add a label on the map


This sample uses a UIToolControl to add a text label on the focus map. For simplicity sake, the label string is hard-coded to "X marks the spot."
A map label is a text element that is added to a map's graphics layer. Text elements can also be added to the page layout's graphics layer - see How to add a text element to the layout for an example of this. For example, we may be labeling a feature on a map in the first case, and giving the entire map a name in layout case.

How to use

  1. Add a new UIToolControl to any toolbar.
  2. Paste the code into the UIToolControl's mouse down event.
  3. Mind the name of the control, the sample assumes it is UIToolControl1.
  4. Modify the text string as desired.
  5. Completely shut down VBA so mouse events fire.
  6. Select the tool and click somewhere on the focus map to add the label.
[VBA]
'Adds a text element (label) to the focus map's graphics layer

Private Sub UIToolControl1_MouseDown(ByVal button As Long, ByVal shift As Long, ByVal x As Long, ByVal y As Long)
    Dim pMxDoc As IMxDocument
    Dim pGraphicsContainer As IGraphicsContainer
    Dim pActiveView As IActiveView
    Dim pTextElement As ITextElement
    Dim pElement As IElement
    
    Set pMxDoc = Application.Document
    Set pGraphicsContainer = pMxDoc.FocusMap
    Set pActiveView = pMxDoc.FocusMap
    
    Set pTextElement = New TextElement
    Set pElement = pTextElement
    
    pTextElement.Text = "X marks the spot"
    pElement.Geometry = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y)
    pGraphicsContainer.AddElement pTextElement, 0
    
    pActiveView.PartialRefresh esriViewGraphics, Nothing, Nothing
End Sub