MapLibre-Geoman Documentation

website·Indexed 34 days ago

https://geoman.io/docs/maplibre

Documentation for MapLibre-Geoman, a toolkit for drawing and editing shapes on MapLibre and Mapbox maps. Includes guides on installation for Free and Pro versions, feature ID management, and detailed usage of draw modes (circles, polygons, lines, freehand, etc.) and edit modes (cut, split, union, rotate, scale, and lasso selection).

Tokens
25.9K
Snippets
161
Records
195
Agent score
70%

What's inside MapLibre-Geoman

  1. Understand and manage Shape Markers Helper Mode

    The Shape Markers Helper Mode is an internal helper that renders draggable vertex and edge markers on a feature during editing (e.g., in change mode). It routes pointer interactions on these markers to the active edit mode and integrates with the Pin helper to ensure shared vertices move together across linked features.

    Because it is an internal helper, it has no toolbar button by default (uiEnabled is false) and is typically activated automatically by edit modes. However, it can be controlled programmatically using the standard mode API.

    map.gm.enableMode('helper', 'shape_markers');
    map.gm.disableMode('helper', 'shape_markers');
    map.gm.toggleMode('helper', 'shape_markers');
    map.gm.isModeEnabled('helper', 'shape_markers');
  2. Split multipolygons using Explode Mode

    Explode Mode splits a multipolygon into separate single-polygon features. It is a selection-gated mode, meaning a multipolygon must be selected first (using Select Mode) before the Explode control becomes enabled. When a multipolygon is exploded, the original feature is removed and a new feature is created for each part of the multipolygon.
  3. Configure named data layers and thematic styling

    Geoman Pro introduces geoman.dataLayers for managing named data layers, including adding, removing, listing, and updating styles. Thematic styling supports get, categorical, step, and interpolate methods, as well as raw renderer-expression arrays for fill, line, and point opacity.
  4. Choose a MapLibre-Geoman starter template

    Depending on your project architecture, choose the appropriate starter implementation for MapLibre-Geoman. All examples are available in the Maplibre-Geoman Examples Repository.

    • Vite: Best for small, framework-independent drawing apps.
    • React, Vue, Preact, or Svelte: Use these for existing framework integrations. Ensure you create one map per mounted container and remove the map when the component unmounts.
    • Next.js: Load the interactive map in a browser-only component, as WebGL and DOM-dependent map code cannot be rendered on the server.
  5. Implement Geoman event listener best practices

    To maintain a performant and stable map application, follow these best practices for Geoman event management:

    1. Error Handling: Wrap event processing in try/catch blocks to prevent a single listener from crashing the event chain.
    2. Cleanup: Use geoman.mapAdapter.off(eventName, handler) to remove listeners when they are no longer needed to prevent memory leaks.
    3. Performance: Use debouncing (e.g., via lodash) for high-frequency events like gm:drag to avoid overloading the main thread.
    4. Organization: Group handlers by category (e.g., draw handlers vs. edit handlers) for better maintainability.
    import { debounce } from 'lodash';
    
    // 1. Error Handling & Registration
    geoman.mapAdapter.on('gm:create', (event) => {
      try {
        // Process event
      } catch (error) {
        console.error('Error processing create event:', error);
      }
    });
    
    // 2. Cleanup
    const handler = (event) => { /* ... */ };
    geoman.mapAdapter.on('gm:create', handler);
    geoman.mapAdapter.off('gm:create', handler);
    
    // 3. Performance for high-frequency events
    const debouncedHandler = debounce((event) => {
      // Process event...
    }, 100);
    geoman.mapAdapter.on('gm:drag', debouncedHandler);
  6. Prepare MapLibre-Geoman for implementation

    Before adapting examples into your project, follow these requirements:

    1. Install packages from the example's lockfile.
    2. Load the matching Geoman and MapLibre CSS.
    3. Assign a height to the map container.
    4. Wait for the gm:loaded event before importing features or enabling draw modes.
    5. For MapLibre GL JS 6 users, configure the worker setup as described in the installation guide.
  7. Enable and manage Click to Edit Helper Mode

    The Click to Edit Helper Mode allows users to put a feature directly into editing mode by clicking it on the map, removing the need to manually enable an edit tool first. This is ideal for 'select and tweak' workflows. It resolves the feature under the cursor across Geoman's persistent sources and activates editing handles. It is compatible with snapping and shape-marker helpers.
    // Enable the mode
    map.gm.enableMode('helper', 'click_to_edit');
    
    // Disable the mode
    map.gm.disableMode('helper', 'click_to_edit');
    
    // Toggle the mode
    map.gm.toggleMode('helper', 'click_to_edit');
    
    // Check if the mode is currently enabled
    const isEnabled = map.gm.isModeEnabled('helper', 'click_to_edit');
  8. Import GeoJSON features with custom or auto-generated IDs

    When importing GeoJSON into Geoman, IDs are handled in three ways: if a top-level id field exists in the GeoJSON, Geoman uses it; if no id is present, Geoman auto-generates a sequential ID; or you can specify a property within the properties object to serve as the ID using the idPropertyName option in importGeoJson.
    // 1. Using top-level ID
    const featureWithId = {
      type: 'Feature',
      id: 'custom-123',
      geometry: { /* ... */ },
      properties: { }
    };
    await gm.features.importGeoJsonFeature(featureWithId);
    
    // 2. Using a property as the ID
    const featureCollection = {
      type: 'FeatureCollection',
      features: [{
        type: 'Feature',
        properties: { customId: 'my-id-123' },
        geometry: { /* ... */ }
      }]
    };
    await gm.features.importGeoJson(featureCollection, { idPropertyName: 'customId' });
  9. Manage global feature selection in Geoman Pro

    Geoman maintains a global selection of features used for selection-gated controls and highlight overlays. The selection is stored as a Set of feature IDs on the features instance.
    // Get current selection (Set<FeatureId>)
    const currentSelection = map.gm.features.selection;
    
    // Set the selection programmatically
    map.gm.features.setSelection(['feature-1', 'feature-2']);
    
    // Clear the selection
    map.gm.features.clearSelection();
  10. Draw a circle using the Circle Mode interaction flow

    To create a circle in Draw Circle Mode, the user follows these steps:

    1. Click on the map to place the circle center.
    2. Move the mouse to adjust the radius.
    3. Click again to finalize the circle.

    Technically, the resulting circle is represented as a GeoJSON polygon with 80 steps by default to ensure smooth rendering.

  11. Draw Polygon user interaction workflow

    The polygon drawing process follows these sequential steps:

    1. Click on the map to place the first vertex.
    2. Move the mouse to see a preview of the polygon segment.
    3. Click to add additional vertices.
    4. Close the polygon by clicking on the first vertex.