Rolando
Rolando

Reputation: 62634

How to "screenshot" leaflet map to base64 with javascript?

I have a leaflet map with some lines and some shapes on it. I want to click a button that allows me to "screenshot" what is in the leaflet map and output a base64 encoded representation of the image. How do I/ is there a way to do this?

Upvotes: 1

Views: 1905

Answers (2)

IvanSanchez
IvanSanchez

Reputation: 19069

It's very complicated. Start by reading https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas. It boils down to creating a <foreignObject> inside a <svg>, cloning a part of the DOM inside that <foreignObject>, then create a Blob for the <svg>, get a URL for that blob, load it into a <img>, and finally access its pixel info.

When you're done reading, fetch the <div> that contains your leaflet map and apply the method described.

AFAIK, there is no Leaflet plugin that implements this technique (yet) - the current print/screenshot plugins use older techniques.

Upvotes: 1

Jieter
Jieter

Reputation: 4229

There is leaflet-image (demo currently broken), which only works for canvas-based layers. Anything HTML (Zoom control, L.DivIcon, attribution etc.) will not show up in the saved image.

Upvotes: 0

Related Questions