### Example: Get Translation String Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Utils.md An example of retrieving a translation string for a tooltip. The output is logged to the console. ```javascript const text = L.PM.Utils.getTranslation('tooltips.placeMarker'); console.log(text); // "Click to place a marker" ``` -------------------------------- ### Install npm Packages Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/README.md Installs all necessary npm packages for development. Run this after cloning the repository. ```bash npm install ``` -------------------------------- ### Example: Get All Parent LayerGroups Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Utils.md Demonstrates how to get all parent groups for a marker and log the number of groups it belongs to. ```javascript const groups = L.PM.Utils.getAllParentGroups(marker); console.log(`Marker is in ${groups.groups.length} groups`); ``` -------------------------------- ### Example: Convert Pixel Radius to Meter Radius Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Utils.md Shows how to convert a pixel radius to meters using `pxRadiusToMeterRadius`. This example logs the result to the console. ```javascript const pixelRadius = 50; const center = L.latLng(51.5, -0.09); const meterRadius = L.PM.Utils.pxRadiusToMeterRadius(pixelRadius, map, center); console.log(`50 pixels = ${meterRadius} meters`); ``` -------------------------------- ### Example: Create Geodesic Polygon Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Utils.md Demonstrates creating a geodesic polygon with a specified center, radius, number of sides, and starting angle, then adding it to the map. ```javascript const center = L.latLng(51.5, -0.09); const points = L.PM.Utils.createGeodesicPolygon(center, 1000, 60, 0, true); const polygon = L.polygon(points, { color: 'blue' }).addTo(map); ``` -------------------------------- ### Complete Leaflet-Geoman Toolbar Configuration Example Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Toolbar.md An example showing how to initialize a Leaflet map, add a customized Leaflet-Geoman Toolbar with various controls, and add a custom export button. It also includes event listeners for draw mode changes and button clicks. ```javascript const map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map); // Add toolbar with customization map.pm.Toolbar.addControls({ position: 'topleft', drawMarker: true, drawRectangle: true, drawPolyline: true, drawPolygon: true, drawCircle: true, drawCircleMarker: false, // Hide circle marker drawText: true, editMode: true, dragMode: true, cutPolygon: true, removalMode: true, rotateMode: true, snappingOption: true, customControls: true, oneBlock: false }); // Add custom button map.pm.Toolbar.createButton({ name: 'exportGeoJSON', block: 'custom', title: 'Export as GeoJSON', className: 'leaflet-pm-button', onClick: () => { const layers = map.pm.getGeomanLayers(); const geojson = { type: 'FeatureCollection', features: layers.map(l => l.toGeoJSON()) }; console.log(JSON.stringify(geojson, null, 2)); }, toggleStatus: false }); // Sync button states with mode changes map.on('pm:drawstart', (e) => { map.pm.Toolbar.toggleButton( `draw${e.shape}`, true, true ); }); map.on('pm:drawend', (e) => { map.pm.Toolbar.toggleButton( `draw${e.shape}`, false ); }); // Respond to button clicks map.on('pm:globaldrawmodetoggeled', (e) => { console.log('Draw mode toggled:', e.shape); }); ``` -------------------------------- ### Complete Leaflet-Geoman Event Handling Example Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md A comprehensive example demonstrating how to set up event listeners for various Leaflet-Geoman events on both the map and individual layers. ```javascript const map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map); // Global map event listeners map.on('pm:drawstart', (e) => { console.log('Drawing started:', e.shape); disableOtherInteractions(); }); map.on('pm:create', (e) => { console.log('New shape created'); saveLayerToDatabase(e.layer); }); map.on('pm:drawend', (e) => { console.log('Drawing finished'); enableOtherInteractions(); }); map.on('pm:globaloptionschanged', (e) => { updateSettings(); }); // Layer-specific event listeners const polygon = L.polygon([[0, 0], [10, 0], [10, 10]]).addTo(map); polygon.on('pm:enable', (e) => { console.log('Edit mode enabled'); }); polygon.on('pm:edit', (e) => { // Called during editing logChanges(e.layer.toGeoJSON()); }); polygon.on('pm:update', (e) => { // Called once when done editing console.log('Editing complete'); saveToDatabase(e.layer); }); polygon.on('pm:vertexadded', (e) => { console.log('Vertex added at', e.latlng); }); polygon.on('pm:markerdragstart', (e) => { console.log('Dragging vertex', e.indexPath); }); polygon.on('pm:markerdragend', (e) => { if (e.intersectionReset) { console.log('Intersection was auto-corrected'); } }); polygon.on('pm:intersect', (e) => { console.warn('Self-intersection detected'); }); polygon.on('pm:remove', (e) => { console.log('Polygon deleted'); deleteFromDatabase(e.layer); }); ``` -------------------------------- ### Get Available Shapes Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md Retrieve a list of all available shape types that can be drawn. This example iterates through the list and logs each drawable shape to the console. ```javascript const availableShapes = map.pm.Draw.getShapes(); availableShapes.forEach(shape => { console.log(`Can draw: ${shape}`); }); ``` -------------------------------- ### Listen for pm:dragstart Event Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md Fired when a layer begins being dragged. Use this to initiate actions when the entire layer starts moving. ```javascript marker.on('pm:dragstart', (e) => { console.log('Started dragging marker'); }); ``` -------------------------------- ### Complete Edit Workflow Example Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Edit.md Demonstrates a full edit workflow for a polygon, including enabling editing with custom options, listening to edit events, and disabling editing. ```javascript const map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map); // Create a polygon const polygon = L.polygon([ [51.5, -0.09], [51.51, -0.1], [51.52, -0.08] ], { color: 'blue' }).addTo(map); // Enable editing with custom options polygon.pm.enable({ allowEditing: true, allowRemoval: true, allowRotation: true, snappable: true, snapDistance: 25, addVertexOn: 'click', removeVertexOn: 'contextmenu', // Validation: prevent removing corner vertices removeVertexValidation: (e) => { const totalVertices = e.layer.getLatLngs()[0].length; return totalVertices > 3; // Keep at least a triangle } }); // Listen to edit events polygon.on('pm:edit', (e) => { console.log('Polygon coordinates:', e.layer.toGeoJSON()); }); polygon.on('pm:vertexadded', (e) => { console.log('Vertex added at:', e.latlng); }); polygon.on('pm:remove', (e) => { console.log('Polygon deleted'); }); // Later, disable editing polygon.pm.disable(); ``` -------------------------------- ### Listening for Language Change Event Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md Example of how to listen for the `pm:langchange` event and log the language transition to the console. ```javascript map.on('pm:langchange', (e) => { console.log(`Language changed from ${e.oldLang} to ${e.newLang}`); }); ``` -------------------------------- ### Install Leaflet-Geoman with npm or pnpm Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/INDEX.md Use npm or pnpm to add the leaflet-geoman-free package to your project. ```bash npm install @geoman-io/leaflet-geoman-free # or pnpm add @geoman-io/leaflet-geoman-free ``` -------------------------------- ### Basic Map Setup with Geoman Controls Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/INDEX.md Initializes a Leaflet map, adds OpenStreetMap tiles, and integrates the Geoman toolbar with custom drawing styles. ```javascript const map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map); // Add toolbar with buttons map.pm.addControls({ position: 'topleft' }); // Set drawing styles map.pm.setPathOptions({ color: '#3388ff', weight: 2 }); ``` -------------------------------- ### Init Hooks Pattern Example Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/architecture.md Shows how Leaflet's init hook system is used to automatically add Geoman functionality to maps and layers upon their creation. ```javascript L.Map.addInitHook(initMap); // Runs for every new map L.Marker.addInitHook(initMarker); // Runs for every new marker ``` -------------------------------- ### Event Delegation Example Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/architecture.md Illustrates parent-to-child event propagation, where events fired on a layer are also propagated to its parent LayerGroups. ```javascript L.PM.Utils._fireEvent(layer, 'pm:edit', data); // Fires on layer AND all parent LayerGroups ``` -------------------------------- ### Complete Drawing Workflow Example Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md This snippet demonstrates a full drawing workflow. It initializes a Leaflet map, adds the Geoman drawing controls, configures various drawing options, sets up an event listener for created layers, and programmatically enables and disables polygon drawing. ```javascript const map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map); // Add toolbar with controls map.pm.addControls({ position: 'topleft' }); // Configure drawing options map.pm.Draw.setOptions({ snappable: true, snapDistance: 25, tooltips: true, cursorMarker: true, pathOptions: { color: '#3388ff', weight: 3, opacity: 0.7 } }); // Listen for drawn layers map.on('pm:create', (e) => { console.log('User created a', e.shape); console.log('Layer coordinates:', e.layer.toGeoJSON()); }); // Enable polygon drawing programmatically map.pm.Draw.Polygon.enable({ allowSelfIntersection: false }); // Later, disable drawing map.pm.Draw.disable(); ``` -------------------------------- ### Mixin Pattern Example Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/architecture.md Demonstrates how classes can include multiple mixins to share functionality. This pattern is used for cross-cutting concerns like event handling and snapping. ```javascript const MyClass = L.Class.extend({ includes: [EventMixin, SnapMixin], // ... implementation }); ``` -------------------------------- ### Set Path Options for Drawn Shapes Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md Define the styling for drawn shapes. The first example sets all shapes to red with specific stroke properties. The second example merges a new color option with existing styles. ```javascript // Set all drawn shapes to red map.pm.Draw.setPathOptions({ color: '#ff0000', weight: 2, opacity: 0.8, dashArray: '5,5' }); ``` ```javascript // Merge with existing options map.pm.Draw.setPathOptions({ color: '#00ff00' }, true); ``` -------------------------------- ### Get All Toolbar Buttons Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Toolbar.md Retrieves all available toolbar button instances. Useful for inspecting the toolbar's current configuration. ```javascript const buttons = map.pm.Toolbar.getButtons(); console.log(Object.keys(buttons)); // ['drawMarker', 'drawPolygon', 'editMode', ...] ``` -------------------------------- ### Get Draw Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Retrieve the current drawing options using getOptions(). ```javascript map.pm.Draw.getOptions(): object ``` -------------------------------- ### Example: Fire Custom Event Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Utils.md An example of firing a custom 'pm:edit' event on a polygon layer. The `propagate` option is set to `false` to prevent the event from bubbling up. ```javascript L.PM.Utils._fireEvent(polygon, 'pm:edit', { layer: polygon }, false); ``` -------------------------------- ### Leaflet-Geoman Utility Functions Example Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Utils.md Demonstrates how to use various utility functions from L.PM.Utils to interact with map layers. This includes finding all editable layers, accessing parent groups, converting circles to polygons, disabling popups, and finding specific coordinates within a polygon. ```javascript // Get all editable layers const layers = L.PM.Utils.findLayers(map); // Work with each layer layers.forEach(layer => { // Get parent groups const { groups } = L.PM.Utils.getAllParentGroups(layer); if (layer.pm.getShape() === 'Circle') { // Convert circle to polygon const polygon = L.PM.Utils.circleToPolygon(layer, 40); polygon.addTo(map); } // Disable popups during interaction L.PM.Utils.disablePopup(layer); }); // Find a specific coordinate in a polygon const polygon = L.polygon([...]).addTo(map); const target = L.latLng(51.5, -0.09); const location = L.PM.Utils.findDeepCoordIndex( polygon.getLatLngs(), target ); if (location.indexPath) { console.log(`Found at path: ${location.indexPath}`); } ``` -------------------------------- ### Get Shape Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Retrieve the current options for a specific shape instance. ```javascript shape.getOptions(): object ``` -------------------------------- ### Set Global Draw Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md Configure global drawing options that apply to all shape drawing modes. This example sets snapping behavior, allows self-intersection, enables cursor markers, and continues drawing after shape completion. ```javascript map.pm.Draw.setOptions({ snappable: true, snapDistance: 30, allowSelfIntersection: false, cursorMarker: true, continueDrawing: true }); ``` -------------------------------- ### Add Toolbar Controls with Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Toolbar.md Adds the toolbar to the map, allowing configuration of which buttons to display and the toolbar's position. Use this to customize the initial toolbar setup. ```javascript map.pm.Toolbar.addControls({ position: 'topright', drawMarker: true, drawPolygon: true, editMode: true, dragMode: false, cutPolygon: true, removalMode: true, rotateMode: true, snappingOption: true, oneBlock: false }); ``` -------------------------------- ### Mode Management Example Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/architecture.md Explains the single active mode principle in Geoman, where enabling one drawing shape automatically disables others. Use `disable()` to turn off all active modes. ```javascript // Enabling one shape disables others map.pm.Draw.enable('Polygon'); // Disables any active shape map.pm.Draw.disable(); // Disables all ``` -------------------------------- ### Build Production Version Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/README.md Compiles and builds the production-ready version of the plugin. ```bash npm run prepare ``` -------------------------------- ### Get Current Drawing Shape Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Get the current drawing shape using getShape(). This is an alias for getActiveShape(). ```javascript map.pm.Draw.getShape(): string | undefined // Alias ``` -------------------------------- ### pm:dragstart Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md Fired when a layer begins being dragged. Provides the layer and shape type. ```APIDOC ## pm:dragstart ### Description Fired when a layer begins being dragged (entire layer movement). ### Event Data - **layer** (L.Layer) - **shape** (string) ### Example ```javascript marker.on('pm:dragstart', (e) => { console.log('Started dragging marker'); }); ``` ``` -------------------------------- ### Run Development Watch Version Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/README.md Compiles and runs a development version of the plugin with live watching for changes. ```bash npm run start ``` -------------------------------- ### Get Leaflet-Geoman Version Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Access the version string of the Leaflet-Geoman library. ```javascript L.PM.version // "2.20.0" ``` -------------------------------- ### Get Available Shapes Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Retrieve a list of all available drawing shapes using getShapes(). ```javascript map.pm.Draw.getShapes(): array ``` -------------------------------- ### Run Unit Tests Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/README.md Executes the unit tests using Vitest. ```bash npm run test:unit ``` -------------------------------- ### Get All Geoman Layers Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Map.md Retrieve all layers that have geoman functionality enabled. Can be returned as an array or a L.FeatureGroup. ```javascript // Get all editable layers as array const layers = map.pm.getGeomanLayers(); ``` ```javascript // Get all editable layers as a FeatureGroup const group = map.pm.getGeomanLayers(true); group.setStyle({ color: 'red' }); ``` -------------------------------- ### Open Cypress Window Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/README.md Opens the Cypress test runner window for interactive E2E testing. ```bash npm run cypress ``` -------------------------------- ### Get List of Available Shapes Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Access the array of available shape names directly from the Draw module. ```javascript map.pm.Draw.shapes // Array: ['Marker', 'CircleMarker', 'Line', ...] ``` -------------------------------- ### Get Active Drawing Shape Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Retrieve the name of the currently active drawing shape using getActiveShape(). ```javascript map.pm.Draw.getActiveShape(): string | undefined ``` -------------------------------- ### Configure Circle Drawing Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md Enable circle drawing with options for resizing, defining minimum and maximum radius, and setting path styles. ```javascript map.pm.Draw.Circle.enable({ resizeableCircle: true, minRadiusCircle: 50, maxRadiusCircle: 1000, pathOptions: { color: '#3388ff' } }); ``` -------------------------------- ### Configure Rectangle Drawing Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md Enable rectangle drawing with options for setting the rectangle angle and defining path styles. ```javascript map.pm.Draw.Rectangle.enable({ rectangleAngle: 0, pathOptions: { color: '#3388ff', weight: 2, opacity: 0.5 } }); ``` -------------------------------- ### Get Geoman Drawn Layers Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Map.md Retrieve only layers that were created with geoman drawing tools. Can be returned as an array or a L.FeatureGroup. ```javascript const drawnLayers = map.pm.getGeomanDrawLayers(); console.log(`Created ${drawnLayers.length} shapes`); ``` -------------------------------- ### Configure CircleMarker Drawing Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md Enable circle marker drawing with options to control resizing and define minimum and maximum radii. ```javascript map.pm.Draw.CircleMarker.enable({ resizeableCircleMarker: false, minRadiusCircleMarker: 10, maxRadiusCircleMarker: 100 }); ``` -------------------------------- ### L.PM.Map Class: Public Properties Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Access instances of L.PM.Draw, L.PM.Toolbar, and the keyboard handler, as well as current global options. ```javascript map.pm.Draw // L.PM.Draw instance map.pm.Toolbar // L.PM.Toolbar instance map.pm.Keyboard // Keyboard handler object map.pm.globalOptions // Current global options ``` -------------------------------- ### Get Layer Shape Type Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Edit.md Determine the geometric shape type of the layer being edited. This can be useful for applying shape-specific logic. ```javascript const shape = polygon.pm.getShape(); console.log(`Editing a ${shape}`); ``` -------------------------------- ### Configure Marker Drawing Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md Enable marker drawing with options to control editability, continuation, and snap distance. ```javascript map.pm.Draw.Marker.enable({ markerEditable: true, continueDrawing: true, snapDistance: 20 }); ``` -------------------------------- ### Get Currently Active Drawing Shape Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md Retrieves the name of the shape that is currently being drawn. Returns undefined if no drawing mode is active. ```javascript const activeShape = map.pm.Draw.getActiveShape(); if (activeShape) { console.log(`Currently drawing: ${activeShape}`); } else { console.log('Not drawing'); } ``` -------------------------------- ### Snapping System Logic Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/architecture.md Explains how the snapping system identifies and applies snap points during drawing or editing. ```text During draw or edit vertex drag: ↓ Calculate cursor/marker position ↓ Snapping mixin checks snap targets: - All other layers (respect snappingOrder) - Vertices of other layers - Segments of other layers - Middle points of segments ↓ For each target, calculate distance ↓ If distance < snapDistance: - Mark as snapped - Move cursor/marker to snap point - Show visual indication (snap marker) ↓ Continue dragging or place vertex ``` -------------------------------- ### Get Global Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Map.md Retrieve all currently configured global options for Geoman. This is useful for inspecting the current state of global settings. ```javascript const options = map.pm.getGlobalOptions(); console.log(options.snappable); // true by default ``` -------------------------------- ### Toolbar (`map.pm.Toolbar`) Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/INDEX.md Manages the toolbar buttons and their behavior. ```APIDOC ## Toolbar (`map.pm.Toolbar`) ### Description Manages the collection of buttons in the drawing and editing toolbar. ### Methods - `getButtons()`: Retrieve all buttons currently in the toolbar. - `addControls(options)`: Add new toolbar controls. - `removeControls()`: Remove all toolbar controls. - `toggleControls(options)`: Show or hide the toolbar controls. - `toggleButton(name, status, disableOthers)`: Toggle the state of a specific button. - `deleteControl(name)`: Remove a specific button from the toolbar. - `createButton(options)`: Add a custom button to the toolbar. - `reinit()`: Reinitialize the toolbar after making changes. ``` -------------------------------- ### Get Current Edit Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Edit.md Retrieve the current configuration options for the edit mode of a layer. This returns an object containing all active options. ```javascript const options = layer.pm.getOptions(); ``` -------------------------------- ### Listen for pm:markerdragstart Event Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md Fired when a vertex marker begins being dragged. Useful for pre-drag operations or logging. ```javascript polygon.on('pm:markerdragstart', (e) => { console.log('Started dragging vertex at:', e.indexPath); }); ``` -------------------------------- ### Get All Parent LayerGroups - Leaflet.PM.Utils Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Utils.md Retrieves all LayerGroup ancestors for a given Leaflet layer. This is useful for understanding the hierarchical structure of layers on the map. ```javascript L.PM.Utils.getAllParentGroups(layer: L.Layer): object ``` -------------------------------- ### Initialize DevPanel with Modules Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/demo/index.html Initializes the Geoman DevPanel and registers modules for state inspection, event logging, layer inspection, and GeoJSON tools. ```javascript const devPanel = new DevPanel(map, { width: 360, collapsed: false, }); devPanel.registerModule(new StateInspector()); devPanel.registerModule(new EventLogger()); devPanel.registerModule(new LayerInspector()); devPanel.registerModule(new GeoJSONTools()); window.devPanel = devPanel; window.map = map; console.log( '%c[Geoman DevDemo] Ready!', 'color: #e94560; font-weight: bold; font-size: 14px;' ); console.log('Press Ctrl+Shift+D to toggle the DevPanel'); console.log('Access map via window.map, devPanel via window.devPanel'); ``` -------------------------------- ### Listen for pm:enable Event Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md Fired when edit mode is enabled for a layer. Use this to react to the start of an editing session for a specific layer. ```javascript polygon.on('pm:enable', (e) => { console.log('Edit mode enabled for:', e.shape); console.log('Layer:', e.layer); }); ``` -------------------------------- ### Global Map Events - Drawing Events Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md Events related to the drawing process, such as when a draw mode starts, ends, or a new shape is created. ```APIDOC ## `pm:drawstart` ### Description Fired when a draw mode is enabled for any shape. ### Event Data ```javascript { shape: string, // 'Marker', 'Polygon', 'Circle', etc. workingLayer: L.Layer, // The layer being drawn (temporary) } ``` ### Example ```javascript map.on('pm:drawstart', (e) => { console.log(`Started drawing: ${e.shape}`); console.log('Working layer:', e.workingLayer); }); ``` ```APIDOC ## `pm:drawend` ### Description Fired when a draw mode is disabled, regardless of whether a shape was created. ### Event Data ```javascript { shape: string, // Shape type being drawn } ``` ### Example ```javascript map.on('pm:drawend', (e) => { console.log(`Finished drawing: ${e.shape}`); }); ``` ```APIDOC ## `pm:create` ### Description Fired when a new layer is created through drawing. ### Event Data ```javascript { shape: string, // Type of shape created layer: L.Layer, // The newly created layer marker: L.Layer // DEPRECATED: Use 'layer' instead } ``` ### Example ```javascript map.on('pm:create', (e) => { console.log('New layer created:', e.shape); console.log('Geometry:', e.layer.toGeoJSON()); // Save to database saveToDatabase(e.layer.toGeoJSON()); }); ``` ```APIDOC ## `pm:centerplaced` ### Description Fired when the center point is placed for Circle or CircleMarker shapes (before radius is set). ### Event Data ```javascript { shape: string, // 'Circle' or 'CircleMarker' workingLayer: L.Layer, // Circle being drawn (if Draw mode) layer: L.Layer, // Circle being edited (if Edit mode) latlng: L.LatLng // Center coordinate } ``` ### Example ```javascript map.on('pm:centerplaced', (e) => { console.log('Circle center placed at:', e.latlng); }); ``` -------------------------------- ### Test Case: Circles and Markers Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/demo/index.html Displays various circles, circle markers, and regular markers on the map. ```javascript clearAllLayers(); // Various circles createCircle([51.505, -0.09], { radius: 500, color: '#e94560' }); createCircle([51.51, -0.08], { radius: 300, color: '#0f3460' }); createCircle([51.5, -0.1], { radius: 200, color: '#4caf50' }); // Circle markers createCircleMarker([51.508, -0.07], { radius: 15, color: '#ff9800' }); createCircleMarker([51.502, -0.085], { radius: 10, color: '#9c27b0', }); // Regular markers createMarker([51.505, -0.09]); createMarker([51.51, -0.08]); createMarker([51.5, -0.1]); map.setView([51.505, -0.09], 14); ``` -------------------------------- ### Vertex Validation: Custom Functions Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Edit.md Provides examples and details on how to use custom validation functions to control vertex addition, removal, and movement during editing. ```APIDOC ## Custom Validation Functions ### Description Use validation functions to control whether vertices can be added, removed, or moved during the editing process. This allows for fine-grained control over geometry modifications. ### Method These functions are set via the `setOptions` method. ### Parameters for Validation Functions Each validation function receives an object with the following properties: * **layer** (L.Layer) - The edited layer. * **marker** (L.Marker) - The vertex marker being validated. * **event** (Event) - The DOM event that triggered the validation. * **indexPath** (array) - The path to the vertex within the layer's coordinate array. ### Example Usage ```javascript polygon.pm.setOptions({ // Prevent removing the first vertex removeVertexValidation: (e) => { const { layer, marker, indexPath } = e; return indexPath[indexPath.length - 1] !== 0; }, // Allow adding vertices only within a certain distance addVertexValidation: (e) => { const { layer, marker } = e; const bounds = layer.getBounds(); return bounds.contains(marker.getLatLng()); }, // Prevent dragging vertices into restricted areas moveVertexValidation: (e) => { const { layer, marker } = e; return marker.getLatLng().lat > 40; // Only north of 40° latitude } }); ``` ### Response * None ### Response Example * None ``` -------------------------------- ### Helper Utility Functions Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Utility functions available through L.PM.Utils for tasks like language translation, geodesic polygon creation, and touch detection. ```javascript // From src/js/helpers/index.js getTranslation(key: string, lang?: string): string createGeodesicPolygon(origin: LatLng, radius: number, sides: number, angle: number, withBearing: boolean): array hasFinePointer(): boolean // Detects mouse vs touch ``` -------------------------------- ### Listen for Geoman Events Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Map.md Subscribe to various events fired by Leaflet-Geoman to react to drawing and editing operations. The 'pm:drawstart' event is shown as an example. ```javascript map.on('pm:drawstart', (e) => { console.log('Drawing started:', e.shape); }); ``` -------------------------------- ### Controlling Event Propagation Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md Demonstrates how to explicitly control event propagation. Use `true` to allow propagation and `false` to prevent it when firing events. ```javascript // Fire event with propagation layer.fire('pm:edit', data, true); // Prevent propagation L.PM.Utils._fireEvent(layer, 'pm:edit', data, false); ``` -------------------------------- ### Enable Drawing on Leaflet Map Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Use map.pm.Draw.enable() to start drawing a specific shape. Pass the shape name as a string and optional configuration options. ```javascript map.pm.Draw.enable(shape: string, options?: object): void ``` -------------------------------- ### DragStartEvent / DragEndEvent Objects Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/types.md These event objects are fired on a layer when dragging starts or ends. They contain the layer being dragged, its shape type, and the source layer. ```javascript { layer: L.Layer, // The layer being dragged shape: string, // Shape type sourceTarget: L.Layer } ``` -------------------------------- ### Configuration: setOptions(options) Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Edit.md Configures the behavior of the edit mode for the layer, allowing customization of snapping, vertex handling, and other editing features. ```APIDOC ## setOptions(options) ### Description Configures edit mode behavior for this layer. Allows customization of various editing aspects like snapping, vertex addition/removal, and layer manipulation. ### Method `layer.pm.setOptions(options: object): void` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **options** (object) - Required - An object containing edit options to configure. * **snappable** (boolean) - Optional - Enable snapping during vertex dragging. Default: `true`. * **snapDistance** (number) - Optional - Pixels to snap within. Default: `20`. * **snapMiddle** (boolean) - Optional - Snap to middle of segments. Default: `false`. * **snapVertex** (boolean) - Optional - Snap to vertices. Default: `true`. * **snapSegment** (boolean) - Optional - Snap to segments. Default: `true`. * **allowSelfIntersection** (boolean) - Optional - Allow self-intersecting lines/polygons. Default: `true`. * **allowSelfIntersectionEdit** (boolean) - Optional - Allow creating self-intersections during edit. Default: `false`. * **preventMarkerRemoval** (boolean) - Optional - Prevent removal of any vertex markers. Default: `false`. * **removeLayerBelowMinVertexCount** (boolean) - Optional - Delete layer if vertices fall below minimum. Default: `true`. * **limitMarkersToCount** (number) - Optional - Max number of vertices (-1 = unlimited). Default: `-1`. * **hideMiddleMarkers** (boolean) - Optional - Hide middle markers on segments. Default: `false`. * **draggable** (boolean) - Optional - Allow dragging entire layer. Default: `true`. * **allowEditing** (boolean) - Optional - Allow editing vertices. Default: `true`. * **allowRemoval** (boolean) - Optional - Allow deleting the layer. Default: `true`. * **allowCutting** (boolean) - Optional - Allow cutting the layer. Default: `true`. * **allowRotation** (boolean) - Optional - Allow rotating the layer. Default: `true`. * **addVertexOn** (string) - Optional - Event to add vertices: 'click' or 'dblclick'. Default: `'click'`. * **removeVertexOn** (string) - Optional - Event to remove vertices: 'click', 'contextmenu', 'dblclick'. Default: `'contextmenu'`. * **removeVertexValidation** (function) - Optional - Function to validate vertex removal. * **addVertexValidation** (function) - Optional - Function to validate vertex addition. * **moveVertexValidation** (function) - Optional - Function to validate vertex movement. * **resizeableCircleMarker** (boolean) - Optional - Allow resizing circle markers in edit mode. Default: `false`. * **resizeableCircle** (boolean) - Optional - Allow resizing circles in edit mode. Default: `true`. * **syncLayersOnDrag** (boolean) - Optional - Sync child layers when parent is dragged. Default: `false`. ### Request Example ```javascript polygon.pm.setOptions({ allowEditing: true, allowRemoval: true, snappable: true, snapDistance: 30, addVertexOn: 'click', removeVertexOn: 'contextmenu', allowRotation: true }); ``` ### Response * None ### Response Example * None ``` -------------------------------- ### map.pm.enableDraw() Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/types.md Enables drawing on the map with specified options. This method can be used to start drawing a specific type of shape or to configure general drawing settings. ```APIDOC ## map.pm.enableDraw() ### Description Enables drawing on the map with specified options. This method can be used to start drawing a specific type of shape or to configure general drawing settings. ### Method ``` map.pm.enableDraw(options: DrawOptionsObject) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (DrawOptionsObject) - Required - An object containing various drawing options. ### Request Example ```json { "finishOn": "click", "cursorMarker": true } ``` ### Response #### Success Response (200) No explicit response body is documented. ``` -------------------------------- ### Handle `pm:drawstart` Event Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md Log the shape type and the temporary working layer when a draw mode begins. This event is useful for performing actions before drawing commences. ```javascript map.on('pm:drawstart', (e) => { console.log(`Started drawing: ${e.shape}`); console.log('Working layer:', e.workingLayer); }); ``` -------------------------------- ### Get Translation String - Leaflet.PM.Utils Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Utils.md Fetches a translated string based on a provided key and an optional language code. Defaults to the active language if none is specified. ```javascript L.PM.Utils.getTranslation(key: string, lang?: string): string ``` -------------------------------- ### pm:markerdragstart Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/events.md Fired when a vertex marker begins being dragged. Provides the layer, the drag event, shape type, and index path of the vertex. ```APIDOC ## pm:markerdragstart ### Description Fired when a vertex marker begins being dragged. ### Event Data - **layer** (L.Layer) - **markerEvent** (Event) - The drag event. - **shape** (string) - **indexPath** (number[]) - Path to vertex being dragged. ### Example ```javascript polygon.on('pm:markerdragstart', (e) => { console.log('Started dragging vertex at:', e.indexPath); }); ``` ``` -------------------------------- ### Path Options Management Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Map.md Configure styling options for all drawn shapes, with the ability to ignore specific shapes or merge options. ```APIDOC ## `setPathOptions(options, optionsModifier)` ### Description Set path styling options for all drawn shapes. You can specify which shapes to ignore or merge the new options with existing ones. ### Method `map.pm.setPathOptions(options: object, optionsModifier?: object): void` ### Parameters #### Request Body - **options** (object) - Required - Path styling options (color, weight, opacity, etc.). - **optionsModifier** (object) - Optional - Modifier flags to control how options are applied. ### Options Modifier Properties - **ignoreShapes** (array) - [] - Array of shape names to skip. - **merge** (boolean) - false - Merge with existing options instead of replacing. ### Example ```javascript // Set path options for all shapes map.pm.setPathOptions({ color: '#ff0000', weight: 3, opacity: 0.8 }); // Set for specific shapes only map.pm.setPathOptions({ color: '#00ff00', weight: 2 }, { ignoreShapes: ['Circle', 'CircleMarker'] }); ``` ``` -------------------------------- ### Example: Calculate Rotated Rectangle Corners Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Utils.md Demonstrates how to use `_getRotatedRectangle` to find the corners of a rotated rectangle. Ensure you have a Leaflet map instance and LatLng objects for the corners. ```javascript const corner1 = L.latLng(51.5, -0.09); const corner2 = L.latLng(51.51, -0.1); const rotation = 45; const corners = L.PM.Utils._getRotatedRectangle(corner1, corner2, rotation, map); // corners = [LatLng, LatLng, LatLng, LatLng] ``` -------------------------------- ### Configuration: getOptions() Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Edit.md Retrieves the current edit options applied to the layer. ```APIDOC ## getOptions() ### Description Retrieves the current edit options configured for this layer. ### Method `layer.pm.getOptions(): object` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Request Example ```javascript const currentOptions = polygon.pm.getOptions(); console.log(currentOptions); ``` ### Response #### Success Response (200) * **Returns** (object) - The current options object for the layer's edit mode. ### Response Example * None ``` -------------------------------- ### L.PM.initialize(options) Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.md Initializes the Leaflet-Geoman plugin by setting up necessary hooks for Leaflet classes. This method is typically called automatically when the library is imported. ```APIDOC ## L.PM.initialize(options) ### Description Initializes the Leaflet-Geoman plugin by setting up necessary hooks for Leaflet classes. This method is typically called automatically when the library is imported. ### Method `L.PM.initialize(options?: object): void` ### Parameters #### Path Parameters - **options** (object) - Optional - Reserved for future configuration ### Response #### Success Response - **void** ``` -------------------------------- ### Toggle Options Based on Drawing Mode Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/configuration.md Control popup behavior during drawing operations. Popups are disabled when drawing starts and re-enabled when drawing ends to prevent interference. ```javascript // Toggle options based on mode map.on('pm:drawstart', (e) => { // Disable popups while drawing map.pm.getGeomanLayers().forEach(layer => { L.PM.Utils.disablePopup(layer); }); }); map.on('pm:drawend', (e) => { // Re-enable popups map.pm.getGeomanLayers().forEach(layer => { L.PM.Utils.enablePopup(layer); }); }); ``` -------------------------------- ### Utilities (`L.PM.Utils`) Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/INDEX.md Provides various utility functions for layer and coordinate operations. ```APIDOC ## Utilities (`L.PM.Utils`) ### Description A collection of helper functions for common tasks related to layers, coordinates, and geometry. ### Methods - `findLayers(map)`: Find all editable layers on the map. - `circleToPolygon(circle, sides, withBearing)`: Convert a circle to a polygon. - `calcMiddleLatLng(map, latlng1, latlng2)`: Calculate the midpoint between two LatLng points. - `findDeepCoordIndex(arr, latlng, exact)`: Find the index of a coordinate within a nested array. - `findDeepMarkerIndex(arr, marker)`: Find the index of a marker within a nested array. - `createGeodesicPolygon(origin, radius, sides, angle, withBearing)`: Create points for a geodesic polygon. - `_getRotatedRectangle(A, B, rotation, map)`: Get the corners of a rotated rectangle. - `_getIndexFromSegment(coords, segment)`: Find the index of a segment within coordinates. - `disablePopup(layer)`: Temporarily disable popups for a layer. - `enablePopup(layer)`: Restore popups for a layer. - `pxRadiusToMeterRadius(radiusInPx, map, center)`: Convert a pixel radius to a meter radius. - `getTranslation(key, lang)`: Get a translated string. - `getAllParentGroups(layer)`: Get all parent LayerGroups of a layer. - `_fireEvent(layer, type, data, propagate)`: Fire a custom event on a layer. ``` -------------------------------- ### L.PM.Toolbar Public Properties Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Key properties of the L.PM.Toolbar instance. ```javascript map.pm.Toolbar.buttons // Object of all buttons map.pm.Toolbar.isVisible // Boolean map.pm.Toolbar.customButtons // Array map.pm.Toolbar.options // Toolbar configuration ``` -------------------------------- ### Implement Custom Vertex Removal Validation Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/errors.md Use the `removeVertexValidation` option to create custom validation logic before allowing vertices to be removed from a layer. This example checks user permissions. ```javascript // ✓ Validate before allowing edits layer.pm.setOptions({ removeVertexValidation: (e) => { if (!userHasPermission()) { console.warn('User cannot remove vertices'); return false; } return true; } }); ``` -------------------------------- ### Configure Text Marker Drawing Options Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/api-reference/L.PM.Draw.md Enable text marker drawing with options for customizing text content, focus behavior, removal on empty, and CSS classes. ```javascript map.pm.Draw.Text.enable({ textOptions: { text: 'Default text', focusAfterDraw: true, removeIfEmpty: true, className: 'custom-text-class' } }); ``` -------------------------------- ### L.PM.Draw Class Methods Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/module-exports.md Provides methods to control the drawing behavior of shapes on the map. You can enable or disable drawing modes, get the active or current shape, and manage drawing options. ```APIDOC ## `L.PM.Draw` Class Methods ### Description Provides methods to control the drawing behavior of shapes on the map. You can enable or disable drawing modes, get the active or current shape, and manage drawing options. ### Methods - **`enable(shape: string, options?: object): void`** Enables a specific drawing shape mode on the map. - **`disable(): void`** Disables the current drawing mode. - **`getActiveShape(): string | undefined`** Returns the name of the currently active drawing shape. - **`getShape(): string | undefined`** Alias for `getActiveShape()`. Returns the name of the currently active drawing shape. - **`setOptions(options: object): void`** Sets global drawing options for all shapes. - **`getOptions(): object`** Retrieves the current global drawing options. - **`setPathOptions(options: object, mergeOptions?: boolean): void`** Sets options for the path (stroke, fill, etc.) of drawn shapes. - **`getShapes(): array`** Returns an array of available shape names that can be drawn. ``` -------------------------------- ### Get Translation with Fallback Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/errors.md Use `L.PM.Utils.getTranslation()` to retrieve localized text. If a key is not found, it falls back to a specified language or 'en'. Custom translations can be provided to prevent missing keys. ```javascript // If 'custom.key' doesn't exist in 'de', falls back to 'en' const text = L.PM.Utils.getTranslation('custom.key'); // Provide custom translations to prevent missing keys map.pm.setLang('en', { custom: { key: 'Custom translation' } }); ``` -------------------------------- ### map.pm.Draw.setOptions() Source: https://github.com/geoman-io/leaflet-geoman/blob/develop/_autodocs/types.md Sets the options for the drawing tools. This allows customization of snapping behavior, tooltips, line styles, and more. ```APIDOC ## map.pm.Draw.setOptions() ### Description Sets the options for the drawing tools. This allows customization of snapping behavior, tooltips, line styles, and more. ### Method ``` map.pm.Draw.setOptions(options: DrawOptionsObject) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (DrawOptionsObject) - Required - An object containing various drawing options. ### Request Example ```json { "snappable": true, "snapDistance": 30, "tooltips": true, "pathOptions": { "color": "#ff0000", "weight": 3 } } ``` ### Response #### Success Response (200) No explicit response body is documented. ```