How to add a text element to the map


This sample uses a UIToolControl to add a text element to the focus map. For simplicity sake, the text string is hard-coded to "X marks the spot."
The text element is added to the map's default graphics layer. Text elements can also be added to the page layout - see the How to add a text element to the layout sample for an example of this. Text added to the map is added in geographic space. This is useful, for example, if you want to annotate a particular feature. Conversely, when you add text to the page layout, you fix the location of the text in page space. This might be useful, fo example, to place a piece of text representing the map title or subject.

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