Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ipyleaflet export map as PNG or JPG or SVG

I have tried to export a visualisation of data with ipyleaflet as PNG or any other file format but i could not find a method that is working. For example in folium there is map.save(path). Is there a library or method in ipyleaflet that i have missed in my research which helps me to accomplish my goal?

here is some example code to generate a map

from ipyleaflet import *
center = [34.6252978589571, -77.34580993652344]
zoom = 10
m = Map(default_tiles=TileLayer(opacity=1.0), center=center, zoom=zoom)
m

I'd like to export this map as an image file without taking a screenshot manually.

I found two sources that allow to export javascript leaflet maps: https://github.com/aratcliffe/Leaflet.print and https://github.com/mapbox/leaflet-image

Unfortunately i was not able to make use of them in python.

like image 868
MBUser Avatar asked Jun 28 '17 10:06

MBUser


2 Answers

My colleague and I found a decent work around for ipyleaflet (python) image export. Here is how it works. The folium library is required for an export. The GeoJson data in this example is already prepared with style properties:

import folium
map = folium.Map([51., 12.], zoom_start=6,control_scale=True)
folium.GeoJson(data).add_to(map)
map.save('map.html')

This is how the result looks: output

The html file can be further processed in python (windows) with subprocess calls to make a PDF or PNG out of it. I hope this helps as the ipyleaflet doc for python is almost non existant.

like image 176
MBUser Avatar answered Sep 16 '22 20:09

MBUser


For generating html, you can use ipywidgets

from ipywidgets.embed import embed_minimal_html
embed_minimal_html('map.html', views=[m])

If you want to make a PNG, you can use ipywebrtc, more specifically:

  • https://ipywebrtc.readthedocs.io/en/latest/ImageRecorder.html
  • https://ipywebrtc.readthedocs.io/en/latest/WidgetStream.html

Or in code:

from ipywebrtc import WidgetStream, ImageRecorder
widget_stream = WidgetStream(widget=m, max_fps=1)
image_recorder = ImageRecorder(stream=widget_stream)
display(image_recorder)

Saving the PNG:

with open('map.png', 'wb') as f:
    f.write(image_recorder.image.value)

Or converting to pillow image for preprocessing:

import PIL.Image
import io
im = PIL.Image.open(io.BytesIO(image_recorder.image.value))
like image 27
Maarten Breddels Avatar answered Sep 16 '22 20:09

Maarten Breddels