1010
1111from __future__ import unicode_literals
1212
13+ import os
14+ import tempfile
15+ import time
16+
1317import json
1418from collections import OrderedDict
1519
@@ -153,10 +157,13 @@ def __init__(self, location=None, width='100%', height='100%',
153157 min_lon = - 180 , max_lon = 180 , max_bounds = True ,
154158 detect_retina = False , crs = 'EPSG3857' , control_scale = False ,
155159 prefer_canvas = False , no_touch = False , disable_3d = False ,
156- subdomains = 'abc' ):
160+ subdomains = 'abc' , png_enabled = False ):
157161 super (LegacyMap , self ).__init__ ()
158162 self ._name = 'Map'
159163 self ._env = ENV
164+ # Undocumented for now b/c this will be subject to a re-factor soon.
165+ self ._png_image = None
166+ self .png_enabled = png_enabled
160167
161168 if not location :
162169 # If location is not passed we center and ignore zoom.
@@ -236,8 +243,7 @@ def __init__(self, location=None, width='100%', height='100%',
236243 """ ) # noqa
237244
238245 def _repr_html_ (self , ** kwargs ):
239- """Displays the Map in a Jupyter notebook.
240- """
246+ """Displays the HTML Map in a Jupyter notebook."""
241247 if self ._parent is None :
242248 self .add_to (Figure ())
243249 out = self ._parent ._repr_html_ (** kwargs )
@@ -246,6 +252,35 @@ def _repr_html_(self, **kwargs):
246252 out = self ._parent ._repr_html_ (** kwargs )
247253 return out
248254
255+ def _to_png (self ):
256+ """Export the HTML to byte representation of a PNG image."""
257+ if self ._png_image is None :
258+ import selenium .webdriver
259+
260+ with tempfile .NamedTemporaryFile (suffix = ".html" ) as f :
261+ fname = f .name
262+ self .save (fname )
263+ driver = selenium .webdriver .PhantomJS (service_log_path = os .path .devnull )
264+ driver .get ('file://{}' .format (fname ))
265+ driver .maximize_window ()
266+ # Ignore user map size.
267+ driver .execute_script ("document.body.style.width = '100%';" )
268+ # We should probably monitor if some element is present,
269+ # but this is OK for now.
270+ time .sleep (3 )
271+ png = driver .get_screenshot_as_png ()
272+ driver .quit ()
273+ self ._png_image = png
274+ return self ._png_image
275+
276+ def _repr_png_ (self ):
277+ """Displays the PNG Map in a Jupyter notebook."""
278+ # The notebook calls all _repr_*_ by default.
279+ # We don't want that here b/c this one is quite slow.
280+ if not self .png_enabled :
281+ return None
282+ return self ._to_png ()
283+
249284 def add_tile_layer (self , tiles = 'OpenStreetMap' , name = None ,
250285 API_key = None , max_zoom = 18 , min_zoom = 1 ,
251286 continuous_world = False , attr = None , active = False ,
0 commit comments