How to convert screen pixels to map units


This function takes a value representing the number of pixels on the screen and returns what that represents in map units. Note that this function uses only the horizontal axis.

How to use

  1. Call this function passing in the number of pixels to convert. The function returns the equivalent map units.
[VBA]
Private Function ConvertPixelsToMapUnits(pixelUnits As Double) As Double
    Dim realWorldDisplayExtent As Double
    Dim pixelExtent As Long
    Dim sizeOfOnePixel As Double
    Dim pDT As IDisplayTransformation
    Dim deviceRECT As tagRECT
    Dim pEnv As IEnvelope
    Dim pActiveView As IActiveView
    Dim pMxDocument As IMxDocument
    
    ' Get the width of the display extents in Pixels
    ' and get the extent of the displayed data
    ' work out the size of one pixel and then return
    ' the pixels units passed in mulitplied by that value
    
    ' QI for the IMxDocument interface from ThisDocument
    Set pMxDocument = ThisDocument
    
    ' QI for the IActiveView interface from the currently selected Map
    Set pActiveView = pMxDocument.FocusMap
    
    ' Get IDisplayTransformation
    Set pDT = pActiveView.ScreenDisplay.DisplayTransformation
    
    ' Get the device frame which will give us the number of pixels in the X direction
    deviceRECT = pDT.DeviceFrame
    pixelExtent = deviceRECT.Right - deviceRECT.Left
    
    ' Now get the map extent of the currently visible area
    Set pEnv = pDT.VisibleBounds
    
    ' Calculate the size of one pixel
    realWorldDisplayExtent = pEnv.Width
    sizeOfOnePixel = realWorldDisplayExtent / pixelExtent
    
    'Multiply this by the input argument to get the result
    ConvertPixelsToMapUnits = pixelUnits * sizeOfOnePixel
End Function