Full code examples

As a comparison between the two ways of scripting in Global Mapper, here are several equivalent Python code examples to the scripting language examples that are shown in the scripting language reference: https://www.bluemarblegeo.com/knowledgebase/global-mapper-22-1/Scripting_Reference/Sample_Scripts.htm

Both the scripting language and Python can be used equally well for creating scripts for use in the Global Mapper app, so it is largely a matter preference on which to use. Writing your scripts in Python may be the better choice if the program requires non-trivial control flow or assigning many variables, or simply if you are more familiar with Python programming. However, some of the functionalities of Global Mapper can only be accessed through the scripting language, as they do not have a corresponding function in the Python. The RunScript function allows these functionalities to still be used. This also means that programs written in the Global Mapper scripting language can be executed in the command line, which is not otherwise possible.

Crop, Merge, and Reproject USGS DRGs into new GeoTIFF and JPEG files

This code imports USGS Digital Raster Graphic (DRG) files and automatically crops the non-map informational collar from the image. Then all the layers are reprojected and exported as GeoTIFF and jpeg formats. When exporting raster data, the desired resolution of the image is required by the ExportRaster function. One way to get a resolution with a ratio faithful to the original shape of the layer is shown in this example.

import globalmapper as gm

# close all layers that may be open
layers_are_open = gm.GetLoadedLayerList()
if layers_are_open:
    arr_ptr, arr_size = layers_are_open
    initial_layers = gm.GM_LayerHandle_array_frompointer(arr_ptr)
    for i in range(arr_size):
        gm.CloseLayer(initial_layers[i])

# import all the layers (should be raster files which have some kind of collar)
gm.LoadLayerList("R:\GeoTIFF\PennsylvaniaGIS\DGLM_PA\O40079C3.TIF", gm.GM_LoadFlags_UseDefaultLoadOpts)
gm.LoadLayerList("R:\GeoTIFF\PennsylvaniaGIS\DGLM_PA\O40079C4.TIF", gm.GM_LoadFlags_UseDefaultLoadOpts)
gm.LoadLayerList("R:\GeoTIFF\PennsylvaniaGIS\DGLM_PA\O40079C5.TIF", gm.GM_LoadFlags_UseDefaultLoadOpts)

# get handles for the loaded layers
arr_ptr, arr_size = gm.GetLoadedLayerList()
layers = gm.GM_LayerHandle_array_frompointer(arr_ptr)

# automatically clip the collar off the image layers
bounds = []
for i in range(arr_size):
    err, opts = gm.GetRasterDisplayOptions(layers[i])
    opts.mAutoClipCollar = True
    gm.SetRasterDisplayOptions(layers[i], opts)
    bounds.append(gm.GetLayerInfo(layers[i]).mGlobalRect)

# set the projection manually
err, proj = gm.LoadProjectionFile("C:\\test data\\UTM 17N.prj")
gm.SetProjection(proj)

# determine the dimensions of the image
bounding_rect = bounds[0]
for rect in bounds[1:]:
    bounding_rect.mMinX = rect.mMinX if (bounding_rect.mMinX > rect.mMinX) else bounding_rect.mMinX
    bounding_rect.mMinY = rect.mMinY if (bounding_rect.mMinY > rect.mMinY) else bounding_rect.mMinY
    bounding_rect.mMaxX = rect.mMaxX if (bounding_rect.mMaxX < rect.mMaxX) else bounding_rect.mMaxX
    bounding_rect.mMaxY = rect.mMaxY if (bounding_rect.mMaxY < rect.mMaxY) else bounding_rect.mMaxY
ratio = abs(bounding_rect.mMaxX - bounding_rect.mMinX) / abs(bounding_rect.mMaxY - bounding_rect.mMinY)
width = 1920
height = width * (1 / ratio)
if height < 1080:   # make sure the exported layers are at least HD
    height = 1080
    width = height * ratio
width = int(width)
height = int(height)


# export the raster layers in the correct size
target_directory = "C:\\exported data\\"
gm.ExportRaster(target_directory + "merged_drg_8bpp.tif", gm.GM_Export_GeoTIFF, 0x0, None, width, height, 0x0)
gm.ExportRaster(target_directory + "merged_drg_gray.tif", gm.GM_Export_GeoTIFF, 0x0, None, width, height, gm.GM_ExportFlags_GenWorldFile + gm.GM_ExportFlags_Grayscale)
gm.ExportRaster(target_directory + "merged_drg.jpg", gm.GM_Export_JPG, 0x0, None, width, height, gm.GM_ExportFlags_GenWorldFile + gm.GM_ExportFlags_GenPRJFile)

Generate Contours from all USGS DEMs in a Folder and Export them to DXF and Shape files

This example shows how to use a raster layer(s) to create elevation contours with custom settings, and then export the resulting vector layer to multiple file formats. Note that there are multiple ways of accessing all files within a particular directory in Python; here, the listdir function from the OS module is used to accomplish it.

import globalmapper as gm
from os import listdir

# close all layers that may be open
layers_are_open = gm.GetLoadedLayerList()
if layers_are_open:
    arr_ptr, arr_size = layers_are_open
    initial_layers = gm.GM_LayerHandle_array_frompointer(arr_ptr)
    for i in range(arr_size):
        gm.CloseLayer(initial_layers[i])

# retrieve all files in the directory with the desired extension(s)
path = "R:\\DEM\\TestDems\\"
dir_files = listdir(path)
filenames = []
for f in dir_files:
    file = f.lower()
    if file.endswith(".dem") or file.endswith(".stds") or file.endswith(".tar") or file.endswith(".gz"):
        filenames.append(file)

# loop over and load in all the found files
for filename in filenames:
    err, arr_ptr, arr_size = gm.LoadLayerList(path + filename, gm.GM_LoadFlags_UseDefaultLoadOpts)
    layer_arr = gm.GM_LayerHandle_array_frompointer(arr_ptr)
    layer = layer_arr[0]

# generate the contour lines at intervals of 50 feet
    contour_params = gm.GM_ContourParams_t()
    contour_params.mIntervalInFeet = 50
    contour_params.mShowProgress = False
    err, contour_layer = gm.GenerateContours(layer, contour_params)

# export the contours
    target_dir = "C:\\exported data\\"
    filename_wo_ext = filename[:filename.index(".")]
    gm.ExportVector(target_dir + filename_wo_ext + "_contours.dxf", gm.GM_Export_DXF, contour_layer, None, gm.GM_VectorExportFlags_HideProgress + gm.GM_VectorExportFlags_GenPRJFile, 0x0)
    gm.ExportVector(target_dir + filename_wo_ext + "_contours.shp", gm.GM_Export_Shapefile, contour_layer, None, gm.GM_VectorExportFlags_HideProgress + gm.GM_VectorExportFlags_GenPRJFile + gm.GM_VectorExportFlags_ExportLines + gm.GM_VectorExportFlags_Export3D, 0x0)

# close the layers after we're done with them
    gm.CloseLayer(layer)
    gm.CloseLayer(contour_layer)

Edit Vector Features Based on an Attribute and Display Label

The code below shows how to load in a Global Mapper package file (.gmp) which contains multiple layers and then modify specific features. One tricky part of this code is that the call GetLineFeature returns a cloned line feature object, which is later freed from memory using FreeLineFeature. Several other functions from the “Vector Layer Query Functions” category on the functions page also return a clone which needs to be freed after use with a corresponding function. Refer to the documentation page of each function for more detail.

import globalmapper as gm

# open the package that contains the relevant vector data
err, arr_ptr, arr_size = gm.LoadLayerList("Z:\\15867\\tiger_wyandotte_sample.gmp", gm.GM_LoadFlags_UseDefaultLoadOpts)
layer_arr = gm.GM_LayerHandle_array_frompointer(arr_ptr)

# iterate over the line features to determine which ones should be modified.
i = 0
feature = gm.GetLineFeature(layer_arr[0], i)    # in this example, line features only show up in layer_arr[0]
while feature:
    attr_name = feature.mFeatureInfo.mAttrList.mName
    attr_val = feature.mFeatureInfo.mAttrList.mVal
    feature_name = feature.mFeatureInfo.mName

# assign the type "railroad" to all features with a CFCC attribute with a value of A41 and a display label with '74' in
# it somewhere (eg "74th Street").
    if attr_name == "CFCC" and attr_val == "A41" and feature_name and "74" in feature_name:
        gm.SetFeatureClass(layer_arr[0], gm.GM_FeatureClass_Line, i, gm.LFC_RAILROAD_OTHER)

# rename any of the features with a CFCC value of A41 to "Burlington Northern Railroad" -- again, for the sake of example.
    if attr_name == "CFCC" and attr_val == "A41":
        gm.SetFeatureLabel(layer_arr[0], gm.GM_FeatureClass_Line, i, "Burlington Northern Railroad")

# be sure to free the deep copies from memory
    gm.FreeLineFeature(feature)
    i += 1
    feature = gm.GetLineFeature(layer_arr[0], i)

Export a set of Loaded Layers to Multiple Shapefiles

Shapefiles can only contain one vector data type at a time: either point, line, or area data. So if you want to export all the loaded vector data of a workspace, you may need to export up to three separate shapefiles. This example shows how to do this in Python, assuming there are already some vector layers loaded in the workspace.

import globalmapper as gm
from os import getcwd

# retrieve the currently loaded vector layers as an array
layers_are_loaded = gm.GetLoadedLayerList()
if not layers_are_loaded:
    print("no layers are loaded, so there is nothing to export")
    quit()
arr_ptr, arr_size = layers_are_loaded
all_layers = gm.GM_LayerHandle_array_frompointer(arr_ptr)
vector_layers = []
for layer in gm.carray_to_list(all_layers, arr_size):
    if gm.GetLayerInfo(layer).mHasVectorData:
        vector_layers.append(layer)

# export individually each of the layers' lines, points, and areas
target_dir = ".\\"  # choose a directory that you may write to
for layer in vector_layers:
    name = gm.GetLayerInfo(layer).mDescription
    name_wo_ext = name[:name.index(".")] if "." in name else name
    err = gm.ExportVector(target_dir + name_wo_ext + "_lines.shp", gm.GM_Export_Shapefile, layer, None, gm.GM_VectorExportFlags_HideProgress + gm.GM_VectorExportFlags_ExportLines, 0x0)
    if not err:
        print("exported line features from " + name + " to " + getcwd() + "\\output\\" + name_wo_ext+ "_lines.shp")
    err = gm.ExportVector(target_dir + name_wo_ext + "_points.shp", gm.GM_Export_Shapefile, layer, None, gm.GM_VectorExportFlags_HideProgress + gm.GM_VectorExportFlags_ExportPoints, 0x0)
    if not err:
        print("exported point features from " + name + " to " + getcwd() + "\\output\\" + name_wo_ext+ "_points.shp")
    err = gm.ExportVector(target_dir + name_wo_ext + "_areas.shp", gm.GM_Export_Shapefile, layer, None, gm.GM_VectorExportFlags_HideProgress + gm.GM_VectorExportFlags_ExportAreas, 0x0)
    if not err:
        print("exported area features from " + name + " to " + getcwd() + "\\output\\" + name_wo_ext + "_areas.shp")

Create Elevation Grids from a Directory of LiDAR

This example shows a fairly common workflow when working with LiDAR data. A directory of LiDAR data is loaded one at a time, and each layer is converted to a raster elevation grid and exported to an image file.

Most of the LiDAR operations available in the Global Mapper application not related to point querying do not have a matching function in the SDK, but are usable in the scripting language. In these cases, calling RunScript allows Python to bridge the gap and provide access to the missing operations. Generating an elevation grid is one of the LiDAR operations that can be accessed by function call in the SDK, albeit with parameter options.

import globalmapper as gm
from os import listdir

# retrieve all lidar files in the directory
source_directory = "V:\\LIDAR\\changeDetection\\White_Sands\\"     # choose a source directory containing lidar data
dir_files = listdir(source_directory)
filenames = []
for f in dir_files:
    file = f.lower()
    if file.endswith(".las") or file.endswith(".laz"):
        filenames.append(file)

# modify the display options
vert_display_opts = gm.GM_VerticalDisplayOptions_t()
vert_display_opts.mHillShading = True
vert_display_opts.mShaderName = "Slope Shader"
gm.SetVerticalDisplayOptions(vert_display_opts)

# loop through all the lidar layers
for file in filenames:
    err, arr_ptr, arr_size = gm.LoadLayerList(source_directory + file, gm.GM_LoadFlags_UseDefaultLoadOpts)
    layers_arr = gm.GM_LayerHandle_array_frompointer(arr_ptr)

# generate an elevation grid with all the loaded layers
    grid_setup = gm.GM_GridGenSetup_t()
    grid_setup.mGridAlg = gm.GM_GridAlg_BinAverage
    grid_setup.mElevUnits = gm.GM_ElevUnit_Meters
    err, grid_layer = gm.GenerateElevationGrid2([layers_arr[0]], grid_setup)

# get the right dimensions for the image
    bounds = gm.GetLayerInfo(grid_layer).mGlobalRect
    ratio = abs(bounds.mMaxX - bounds.mMinX) / abs(bounds.mMaxY - bounds.mMinY)
    width = 1920
    height = width * (1 / ratio)
    if height < 1080:   # make sure the exported layers are at least HD
        height = 1080
        width = height * ratio
    width = int(width)
    height = int(height)

# export the raster image
    target_dir = ".\\"  # choose a directory that you may write to
    gm.ExportRaster(target_dir + file + " elevation grid.jpg", gm.GM_Export_JPG , grid_layer, None, width, height, 0x0)
    gm.CloseLayer(layers_arr[0])
    gm.CloseLayer(grid_layer)