I'm making an Angular4 app with leaflet maps and I need to export the current view of a map in one JPG image. Something like taking a screen shot but just the map with markers and polylines.
So, first I put markers and polylines in my leaflet map, and then I have to press a button that export the current view (including markers an polylines) in a JPG or PNG image and then ask me where to save the image.
Is there any way to do that? Some plugin that I could use?
Please help
Here is a rough implementation, substitute in your own relevant code.
The last function saveSvgAsPng()
is from this library https://github.com/exupero/saveSvgAsPng, it allows you to save a <svg>
element into a PNG or data url
function convertToPng() {
const mapContainerRect = yourLeafletMapInstance.getContainer().getBoundingClientRect();
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const mapTiles = document.querySelectorAll('classe-of-map-tile-image');
const markers = document.querySelectorAll('classe-of-marker');
const polylines = document.querySelectorAll('polyline-element-class');
svg.setAttribute('width', mapContainerRect.width;
svg.setAttribute('height', mapContainerRect.height);
mapTiles.forEach(tile => {
const image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
const tileRect = tile.getBoundingClientRect();
image.setAttribute('width', tileRect.width);
image.setAttribute('height', tileRect.height);
image.setAttribute('x', tileRect.left - mapContainerRect.left);
image.setAttribute('y', tileRect.top - mapContainerRect.top);
image.setAttribute('xlink:href', tile.src);
svg.appendChild(image);
});
markers.forEach(marker => {
const image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
const markerRect = marker.getBoundingClientRect();
image.setAttribute('width', markerRect.width);
image.setAttribute('height', markerRect.height);
image.setAttribute('x', markerRect.left - mapContainerRect.left);
image.setAttribute('y', markerRect.top - mapContainerRect.top);
image.setAttribute('xlink:href', marker.src);
svg.appendChild(image);
});
polylines.forEach(polyline => {
const copy = polyline.cloneNode();
svg.appendChild(copy);
});
saveSvgAsPng(svg, "map.png");
}