Skip to main content

Adding Leaflet-Geoman-Pro-Screenshot Plugin

The Leaflet-Geoman-Pro-Screenshot plugin is an add-on for the Leaflet-Geoman-Pro library. It enables users to take screenshots of their maps, complete with customizable options for captions, cropping, and styling. This plugin is dependent on the Leaflet-Geoman-Pro library being already added and initialized.

This document provides an overview of the plugin, its options, and how to integrate it into your project.


Prerequisites

Before adding the Leaflet-Geoman-Pro-Screenshot plugin, ensure you have the Leaflet-Geoman-Pro library installed and initialized in your project.


Installation

1. Install Library

Install the screenshot library via npm or import it into your project as needed.

npm install @geoman-io/leaflet-geoman-pro-screenshot

The leaflet-geoman-pro-screenshot plugin is available through Geoman's NPM registry at npm.geoman.io. To access it, you'll need an API key - the same one used for the @geoman-io/leaflet-geoman-pro plugin. Custom NPM registry setup follows the same process as the pro plugin. For detailed setup instructions, see the ⭐ Pro Version installation guide. If you have already setup the pro plugin, you can skip this step.

2. Add the Screenshot Plugin

Import the plugin and initialize it after adding Geoman controls:

import "@geoman-io/leaflet-geoman-pro-screenshot";
import "@geoman-io/leaflet-geoman-pro-screenshot/dist/leaflet-geoman-pro-screenshot.css";

3. Configure the Plugin

L.PM.initializeGeomanScreenshot(map, screenshotOptions);

Integration

Example Code

Here is how to integrate and configure the plugin in your project:

import "@geoman-io/leaflet-geoman-pro-screenshot";
import "@geoman-io/leaflet-geoman-pro-screenshot/dist/leaflet-geoman-pro-screenshot.css";

...

map.pm.addControls(); // Add Geoman controls

const screenshotOptions = {
format: 'image', // Output format of the screenshot
caption: 'This is a caption', // Caption to include in the screenshot
};

// Initialize the screenshot plugin
L.PM.initializeGeomanScreenshot(map, screenshotOptions);

// Listen for screenshot events
map.on('pm:prepare-screenshot pm:screenshot', console.log);

Make sure the plugin is initialized after the Geoman controls are added using map.pm.addControls().


Options

The GeomanScreenshot plugin provides the following customizable options:

General Options

OptionTypeDefaultDescription
formatstringblobOutput format of the screenshot. Options: blob, image.
cropImageByInnerWHbooleantrueCrops blank opacity from image borders.
domtoimageOptionsobject{}Additional options passed to the dom-to-image library. See https://github.com/tsayen/dom-to-image.
hideElementsWithSelectorsstring[]['.leaflet-control-container']CSS selectors for elements to hide in the screenshot. Elements must be children of the map container. Default value hides the leaflet and geoman control containers.
caption`stringfunction`null
captionFontSizenumber15Font size of the caption.
captionFontstringArialFont family of the caption.
captionColorstringblackText color of the caption.
captionBgColorstringwhiteBackground color of the caption.
captionOffsetnumber5Offset between the caption and the image.

Control Options

OptionTypeDefaultDescription
hideControlbooleanfalseHides the control button if set to true.
blockstringcustomSpecifies the Geoman toolbar block for the button.
titlestringTake ScreenshotTooltip text displayed when hovering over the button.
classNamestringleaflet-pm-icon-geoman-screenshotCSS class for the button.
onClickfunctionundefinedCustom click handler for the button. Defaults to taking a screenshot.

Events

The plugin fires the following events:

pm:prepare-screenshot

Triggered when the screenshot process starts. Use this event to prepare the map (e.g., hide elements or add styles).

map.on('pm:prepare-screenshot', () => {
console.log('Preparing...');
});

pm:screenshot

Triggered when the screenshot is completed. The event contains the screenshot image as a Base64-encoded string:

map.on('pm:screenshot', (e) => {
console.log(e.image); // Base64-encoded screenshot image
});

Other example handlers

Adding screenshot to page

// Creates an <img> element and displays the screenshot directly on the page
map.on('pm:screenshot', (e) => {
let img = document.createElement('img');
img.src = e.image;
document.body.appendChild(img);
});

Downloading screenshot

// Automatically downloads the screenshot as a PNG file
map.on('pm:screenshot', (e) => {
const link = document.createElement('a');
link.href = e.image;
link.download = 'screenshot.png';

document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});

Send to Webhook and Show Modal

map.on('pm:screenshot', async (e) => {
try {
// Prepare metadata
const metadata = {
timestamp: new Date().toISOString(),
mapCenter: map.getCenter(),
zoomLevel: map.getZoom(),
imageData: e.image
};

// Send to webhook
const response = await fetch('https://api.example.com/screenshots', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(metadata)
});

const result = await response.json();

// Show result in modal
const modal = document.createElement('div');
modal.innerHTML = `
<div class="modal-content">
<h3>Screenshot Uploaded</h3>
<img src="${result.url}" alt="Map Screenshot" />
<p>ID: ${result.id}</p>
<button onclick="this.parentElement.remove()">Close</button>
</div>
`;
modal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);display:flex;justify-content:center;align-items:center;';
document.body.appendChild(modal);
} catch (error) {
console.error('Failed to process screenshot:', error);
}
});

External API

After the screenshot plugin is initialized, it is available at:

  // map is a leaflet instance
map.pm.Screenshot

The Screenshot plugin exposes the following methods:

takeScreenshot

takeScreenshot(format?: string): Promise<string>

Takes a screenshot of the map and returns a Promise that resolves with the screenshot image.

Parameters:

  • format (optional): string - The output format of the screenshot. Defaults to the format specified in the options ('blob' by default).
    • Possible values: 'blob' or 'image'

Returns:

  • Promise<string> - A promise that resolves with the screenshot image (as a base64 string for 'image' format or Blob URL for 'blob' format)

Events fired:

  • Fires 'pm:prepare-screenshot' when starting
  • Fires 'pm:screenshot' with the image data when complete

Example usage:

// Take screenshot with default format
map.pm.Screenshot.takeScreenshot()
.then(image => {
console.log('Screenshot taken:', image);
});

// Take screenshot with specific format
map.pm.Screenshot.takeScreenshot('image')
.then(image => {
const img = document.createElement('img');
img.src = image;
document.body.appendChild(img);
});

setOptions

setOptions(options: object): void

Updates the screenshot plugin configuration with new options.

Parameters:

  • options (required): object - An object containing the options to update. See the Options section above for available options.

Example usage:

// Update single option
map.pm.Screenshot.setOptions({
caption: 'New Caption'
});

// Update multiple options
map.pm.Screenshot.setOptions({
caption: 'New Caption',
captionFontSize: 20,
control: {
title: 'New Button Title',
hideControl: true
}
});

[Rest of the document remains the same...]

Advanced Example

Here is a more advanced example with all options configured:

...
// Import geoman pro
import "@geoman-io/leaflet-geoman-pro";
import "@geoman-io/leaflet-geoman-pro/dist/leaflet-geoman.css";
// Import geoman pro screenshot
import "@geoman-io/leaflet-geoman-pro-screenshot";
import "@geoman-io/leaflet-geoman-pro-screenshot/dist/leaflet-geoman-pro-screenshot.css";
...

map.pm.addControls();

const screenshotOptions = {
format: 'image',
caption: 'Custom Caption',
captionFontSize: 20,
captionFont: 'Verdana',
captionColor: 'blue',
captionBgColor: 'yellow',
hideElementsWithSelectors: ['.leaflet-control-container', '.custom-ui'],
control: {
hideControl: false,
title: 'Capture Map',
className: 'custom-screenshot-button',
onClick: () => {
console.log('Screenshot button clicked!');
},
},
};

L.PM.initializeGeomanScreenshot(map, screenshotOptions);

map.on('pm:prepare-screenshot', () => {
console.log('Preparing screenshot...');
});

map.on('pm:screenshot', (e) => {
console.log('Screenshot taken:', e.image);
});

Summary

The Leaflet-Geoman-Pro-Screenshot plugin is a powerful add-on for capturing screenshots of your map with customizable options. By integrating it with the Leaflet-Geoman-Pro library, you can easily add screenshot capabilities to your mapping application. Make sure to initialize it after adding the Geoman controls, and configure the options to fit your specific needs.