pbugnion / gmaps

Google maps for Jupyter notebooks
https://jupyter-gmaps.readthedocs.io/en/stable/
Other
760 stars 146 forks source link

Ability to add layers after the map is rendered #186

Open mhamilton723 opened 7 years ago

mhamilton723 commented 7 years ago

Hey, Great codebase, however I am struggling to figure out how to update the layers of a gmap figure in a way that the displayed widget will re-render. Is this currently possible?

pbugnion commented 7 years ago

Thanks for raising this!

At the moment, you cannot add layers after the figure has been rendered (sorry -- that could have been documented better). The ability to add / remove layers after the map has been rendered would be great.

One possible workaround is to embed the map in a container widget (like an HBox) and just rerender a new map inside the HBox:


import ipywidgets as widgets

import gmaps
gmaps.configure(api_key='stuff')

class UpdatingMap(object):
    def __init__(self):
        self.layers = []
        self.map_kwargs = {
            'layout': {'width': '600px', 'height': '400px'}
        }
        self.container = widgets.HBox(
            [gmaps.Map(layers=self.layers, **self.map_kwargs)], 
        )

    def add_layer(self, layer):
        self.layers.append(layer)
        self.container.children = [
            gmaps.Map(layers=self.layers, **self.map_kwargs)
        ]

    def display(self):
        return self.container

You can then use:

fig = UpdatingMap()
fig.display()

If you now write:

fig.add_layer(gmaps.traffic_layer())

... the map updates (or rather, it's replaced by an entirely new map).

Obviously, you need to migrate any state that you want to keep from the old map to the new map. At the moment, this is possible for some things but not others. For instance, there is no way to get the current zoom and center of a map.


Anyone interested in implementing this correctly needs to:

mhamilton723 commented 7 years ago

Thanks for the fast and thorough response, one this i would really like to do is add data to an existing heatmap layer and have it re-render. Is this also not possible currently?

pbugnion commented 7 years ago

Dynamically updating the data underlying the heatmap is a slightly different issue. I've reraised this in issue #188.